Definition and Usage..
The cloneNode() method creates a copy of a node, and returns the clone.
The cloneNode() method clones all attributes and their values.
Tip: Use the appendChild() or insertBefore() method to insert the cloned node to the document.
Tip: Set the deep parameter value to true if you want to clone all descendants (children), otherwise false
Syntax: node.cloneNode(deep)
Different way to how to declare cloneNode() in program.
CODING:The cloneNode() method creates a copy of a node, and returns the clone.
The cloneNode() method clones all attributes and their values.
Tip: Use the appendChild() or insertBefore() method to insert the cloned node to the document.
Tip: Set the deep parameter value to true if you want to clone all descendants (children), otherwise false
Syntax: node.cloneNode(deep)
Different way to how to declare cloneNode() in program.
<!DOCTYPE html>
<html>
<style>
h1,p{
background-color:lightgreen;
}
</style>
<body>
<div id="List1"><h1>HTML</h1><ul id="ul"><li>1</li><li>2</li></ul></div>
<div id="List2"></div>
<button onclick="tagText()">Copy h1 Tag and Text</button>
<button onclick="tag()">Copy only li Tag</button>
<script>
function tagText() {
var itm = document.getElementById("List1").firstChild;
var cln = itm.cloneNode(true);
document.getElementById("List2").appendChild(cln);
}
function tag() {
var itm = document.getElementById("ul").lastChild;
var cln = itm.cloneNode(false);
document.getElementById("List2").appendChild(cln);
}
</script>
<span><br>Click the button to copy an item from one list to another.<br>
<span>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be cloned.</span>
</body>
</html>
<html>
<style>
h1,p{
background-color:lightgreen;
}
</style>
<body>
<div id="List1"><h1>HTML</h1><ul id="ul"><li>1</li><li>2</li></ul></div>
<div id="List2"></div>
<button onclick="tagText()">Copy h1 Tag and Text</button>
<button onclick="tag()">Copy only li Tag</button>
<script>
function tagText() {
var itm = document.getElementById("List1").firstChild;
var cln = itm.cloneNode(true);
document.getElementById("List2").appendChild(cln);
}
function tag() {
var itm = document.getElementById("ul").lastChild;
var cln = itm.cloneNode(false);
document.getElementById("List2").appendChild(cln);
}
</script>
<span><br>Click the button to copy an item from one list to another.<br>
<span>Try changing the <em>deep</em> parameter to false, and only an empty LI element will be cloned.</span>
</body>
</html>
Comments
Post a Comment