Dom replication cloneNode node and insert node appendChild ()

Source: Internet
Author: User
2. Copy the node.
CloneNode (boolean ):
It has a parameter.
Var mes = document. createTextNode ("hello world ");
Var container = document. createElement ("p ");
Container. appendChild (mes );
Document. body. appendChild (container );
Var newpara = container. cloneNode (true); // difference between true and false
Document. body. appendChild (newpara );
Note:
True: <p> aaaa </p> clone.
False: Only <p> </p> is cloned, and the text in it is not cloned.
You can write an example by yourself and use firebug to see it.
The new node after cloning will not be automatically inserted into the document like createTextNode. AppendChild () is required ();
Another note: if the id is the same after cloning, do not forget to use setAttribute ("id", "another_id");
Change the ID of the new node.
3. Insert nodes.
AppendChild ():
Append a subnode to the element, and insert the new node to the end.
Var container = document. createElement ("p ");
Var t = document. createTextNode ("cssrain ");
Container. appendChild (t );
Document. body. appendChild (container );
He often works with createElement (), createTextNode (), and cloneNode.
In addition, appendChild () can be used not only to append new elements, but also to move existing elements in the document.
See the following example:
<P id = "msg"> msg </p>
<P id = "content"> content </p>
<P id = "aaa"> aaaaaaaa </p>
<Script>
Var mes = document. getElementById ("msg ");
Var container = document. getElementById ("content ");
Container. appendChild (mes );
</Script>
// It is found that msg is placed behind content.
Js internal processing method:
Delete the object whose ID is msg from the document and insert the object to the content as the last node of the content.
Result:
<P id = "content">
Content
<P id = "msg"> msg </p>
</P>
<P id = "aaa"> aaaaaaaa </p>

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.