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