Differences between childNodes and children for DOM elements operated by JavaScript
For DOM elements, children is a sub-Object of the DOM Object type, excluding textnodes invisible between tags. childNodes includes TextNode objects invisible between tags.
Take a look at the tests for children and childNodes in chrome:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<! DOCTYPE html> <Html> <Head> <Meta charset = "UTF-8"> <Title> Insert title here </title> </Head> <Body> <Div id = "div1" class = "div"> <Span id = "s1" class = "sp" lang = "zh-cn"> </Span> </Div> </Body> <Script type = "text/javascript"> Function test (){ Var o = document. getElementById ("div1 "); Var child = o. children; Console. log ("div1.children running result :"); For (I = 0; I <child. length; I ++ ){ Console. log (child [I]. tagName ); } Console. log (""); Child = o. childNodes; Console. log ("div1.childNodes running result :"); For (I = 0; I <child. length; I ++ ){ Console. log (child [I]. tagName ); } } Test (); </Script> </Html> |
The test results are as follows:
1 2 3 4 5 6 7 |
Div1.children running result: SPAN Div1.childNodes running result: Undefined SPAN Undefined |
There are two undefined nodes in the result of the above childNodes set, which are the textnodes with nodeType = 3.
If you write the HTML code as follows, the results of children and childNodes are no different.
1 2 3 |
<Body> <Div id = "div1" class = "div"> <span id = "s1" class = "sp" lang = "zh-cn"> </span> </div> </Body> |
No other differences were found in the HTML elements such as document, head, body, and div.