Many times we use a for to generate multiple structures with the same structure, so we need to write a lot of createelement, setattribute, appendchild code.
But in fact we only need to have an HTML template, we can use the CloneNode method to clone an existing node, including its child nodes.
The following is the CloneNode method prototype:
Newelement Oldelement.clonenode (bool deep);
This method has only one parameter deep, a Boolean value, and if true, the clone oldelement this and its child nodes, otherwise it is only possible for the node itself.
The return value is a cloned node newelement.
Here are the test code, test.htm and Test.js files.
Copy Code code as follows:
<!--test.htm-->
<title>test of CloneNode method</title>
<script type= "Text/javascript" src= "Test.js" ></script>
<body>
<div id= "Main" >
<div id= "div-0" >
<span>cloud018 said, </span>
<span> "Hello World!!!" </span>
</div>
</div>
</body>
Code
Copy Code code as follows:
Test.js
Window.onload = function () {
var sourcenode = document.getElementById ("div-0"); Get the cloned Node object
for (var i = 1; i < 5; i++) {
var Clonednode = Sourcenode.clonenode (true); Clone node
Clonednode.setattribute ("id", "div-" + i); Modify ID value to avoid duplicate ID
SourceNode.parentNode.appendChild (Clonednode); Insert a cloned node in the parent node
}
}
The results of the Web page loading are as follows:
With Google Chrome developer tools, you can see that the DIV-0 node structure has been replicated.
When the deep parameter of CloneNode is set to False, only div-0 the node itself is cloned, and his child node (that is, its contents) is not replicated.
Copy Code code as follows:
var Clonednode = Sourcenode.clonenode (false);