DOM creation node createElement ():

Source: Internet
Author: User
As a js-DOM developer, you must know some DOM methods:
1. Create a node.
CreateElement ():
Var a = document. createElement ("p ");
It creates an element node, so nodeType is equal to 1.
A. nodeName will return p;
Note: The new element node created by the createElement () method will not be automatically added to the document. Since it is not added to the document, it indicates that it is still in a free state. Therefore, it does not have the nodeParent attribute.
If you want to add it to the document, you can use the appendChild (), insertBefore (), or replaceChild () methods. Of course, in the previous example, we wrote an insertAfter () method;
For example:
Var a = document. createElement ("p ");
Document. body. appendChild ();
Note: appendChild () is added to the end of the document by default. That is, the lastChild subnode.
If you want to add it to a certain place, you can use insertBefore ().
If you want to add attributes to an element before it is inserted. You can do this:
Var a = document. createElement ("p ");
A. setAttribute ("title", "my demo ");
Document. body. appendChild ();
CreateTextNode ():
Var B = document. createTextNode ("my demo ");
It creates a text node, so nodeType is equal to 3.
B. nodeName will return # text;
Like createElement (), nodes created with createTextNode () are not automatically added to the document. You must use the appendChild (), insertBefore (), or replaceChild () methods.
He often works with createElement (). Do you know why? (One element node and one text node .)
Var mes = document. createTextNode ("hello world ");
Var container = document. createElement ("p ");
Container. appendChild (mes );
Document. body. appendChild (container );

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.