JavaScript code _javascript Techniques for cloning nodes using the CloneNode method

Source: Internet
Author: User
Tags chrome developer chrome developer tools

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);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.