JavaScript operates on the childNodes and children differences of the DOM element

  • 2020-05-19 04:16:10
  • OfStack

For the DOM element, children is a child object of type DOM Object, not including TextNode, which exists invisibly between tag and childNodes, and TextNode, which exists invisibly between tag and childNodes.

Let's look at the test of children and childNodes in chrome environment:


<!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 The results :");
 for(i = 0; i < child.length; i++){
   console.log(child[i].tagName);
  }
 
 console.log("");
 child = o.childNodes;
 console.log("div1.childNodes The results :");
 for(i = 0; i < child.length; i++){
   console.log(child[i].tagName);
  }
 
 }
 
 test();

</script>
</html>


The test results are as follows:


 div1.children The results :
 SPAN

 div1.childNodes The results :
 undefined
 SPAN
 undefined

The result of the childNodes set above has two undefined nodes, which together are TextNode with nodeType=3.

If you write the HTML code in the following style, there is no difference between the children and childNodes results.


<body>
 <div id="div1" class="div"><span id="s1" class="sp" lang="zh-cn"></span></div>
</body>

No other differences were found in the measurement of HTML elements such as document, head, body and div


Related articles: