This article first blog Park: http://jscode.cnblogs.com, reprint please indicate the source.
Regarding the differences between element and node, the differences between cilldren and childnodes are unclear. This article attempts to let everyone understand the differences between these concepts.
Node is the common name of any type of object in the DOM hierarchy. node has many types, such as element nodes, attribute nodes, text nodes, and comment nodes. It is distinguished by nodetype, common examples include:
Node Type |
Nodetype |
Element |
1 |
Attribute ATTR |
2 |
Text text |
3 |
Comment comments |
8 |
Document |
9 |
For more node types, refer to: https://developer.mozilla.org/en-US/docs/DOM/Node.nodeType? Redirectlocale = en-US & redirectslug = nodetype
Element inherits the node class, that is, element is one of multiple types of node.That is, when nodetype is 1, node is elementnode. In addition, element extends node and has attributes such as ID, class, and children.
The above is the difference between element and node.
So what is the node or element obtained using document. getelementbyid ("XXX? Let's test:
<! Doctype html > < Html > < Head > < Meta Charset = "UTF-8" > < Title > Demo </ Title > </ Head > < Body > < Div ID = "Test" > < P > One </ P > < P > Two </ P > </ Div > < Script > VaR Odiv = Document. getelementbyid ( " Test " ); Console. Log (odiv Instanceof Node ); // True Console. Log (odiv Instanceof Element ); // True </ Script > </ Body > </ Html >
We can see thatUsing document. getelementbyid ("XXX") to get both element and Node.
Children is the attribute of element and childnodes is the attribute of node., Let's test it again:
<! Doctype html > < Html > < Head > < Meta Charset = "UTF-8" > < Title > Demo </ Title > </ Head > < Body > < Div ID = "Test" > < P > One </ P > < P > Two </ P > </ Div > < Script > VaR Odiv = Document. getelementbyid ( " Test " ); Console. Log (odiv. Children [ 0 ] Instanceof Node ); // True Console. Log (odiv. Children [ 0 ] Instanceof Element ); // True Console. Log (odiv. childnodes [ 0 ] Instanceof Node ); // True Console. Log (odiv. childnodes [ 0 ] Instanceof Element ); // False Console. Log ( Typeof Odiv. childnodes [ 0 ]. Children ); // Undefined Console. Log ( Typeof Odiv. childnodes [ 0 ]. Childnodes ); // Object </ Script > </ Body > </ Html >
Through the aboveCodeWe can see that the children [0] of element is still an element, an instance of node and element, and the childndoes [0] of node is a node instance, not an element instance.
At the same time,The children attribute of node is undefined..
Do you understand the above?