javascript to create a DOM node - insert - delete operations --- appendChild () Caution!

What is a node?

HTML document, it was all nodes.

The entire document, a document node; each html element, is an element node; html each attribute is attribute node; each comment is a comment node; html text within, a text node.

DOM HTML document will be considered as a tree structure, called a node tree.

All nodes in the tree nodes can access or modify by js.

Node node in the tree has a hierarchical relationship --- parent (parent), the child (child), compatriots (sibling), the parent has the child, siblings have the same parent.

 Creating nodes

document.creatElement ( 'name tag') to create a node --- label names are not case sensitive.

Another method is to copy existing nodes, cloneNode (), fill out the brackets true or false. When false, only perform a shallow copy, only copy the label that is the role of his child elements are not copied.

clonNode (true) , the results are as follows:

 

clonNode (false) , the results are as follows:

 

 

 Insert Node

appendChild() 或者 insertBefore()

appendChild () call on the parent element, the new element is inserted into the parent element in the final position.

insertBefore () call on the parent element, receiving two parameters, one parameter: the parent element to be added; Reference 2: child elements of a parent element exists. The elements to be added in front of which element is placed.

Note that, when calling these two methods, if a node already existing re-inserted, then the node to the original position automatically deleted, and reinserted at a new location.

Example: according to the contents of the label li, li descending order.

code show as below:

 After the results of the implementation of the following:

 Arr array of all the original li li, li is not newly added, so that when the appendChild (), only the equivalent of a rearranged order of the original li.

 And create a new label li will add an element in the foundation that already exists on.

 

Delete Node

removeChild () --- delete a node from the document tree. It should be noted that this method is on the parent node you want to delete a node calls node to be removed as a parameter of the method.

The results are as follows:

replaceChild () --- delete a child node, and replacing it with a new node. Reference 1: new node; Reference 2: a need for alternative nodes.

Example: to add a tag to the parent element p div

 

The results are as follows:

 

 

Guess you like

Origin www.cnblogs.com/yznotes/p/12637286.html