Properties Introduction
Children
Children: Returns a collection of all the immediate child nodes of the parent element, noting that children only returns HTML element nodes, excluding text nodes and attribute nodes.
ChildNodes
childnodes: Returns a collection of all the immediate child nodes of the parent element, noting that unlike children, ChildNodes returns HTML element nodes, attribute nodes, and text nodes. Code Demo
<!
DOCTYPE html>
The above code is the output of #test childnodes and children respectively in the console.
The code runs the result diagram as follows:
As you can see, the test.childNodes.length is 7, which includes two text nodes, three HTML element nodes and two return-generated nodes (that is, the #test shown in the console);
Sometimes you need to get the first HTML child node (a non-attribute/text node) of the specified element, and the easiest thing to think about is the FirstChild property. If there is a newline and a space before the first HTML node in the code, then the FirstChild return is not what you want. can use NodeType to judge under.
function GetFirst (elem) {for
(var i=0,e;e=elem.childnodes[i++];) {
if (e.nodetype==1) return
e;
}
}
The test.children.length is 3, just three HTML element nodes. It should be noted here that children contains annotation nodes in IE.