Home  >  Article  >  Web Front-end  >  Differences between childNodes and children when JavaScript operates DOM elements_javascript skills

Differences between childNodes and children when JavaScript operates DOM elements_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:06:381234browse

For DOM elements, children refers to sub-objects of the DOM Object type, excluding the TextNode objects that exist invisible between tags, and childNodes includes the TextNode objects that exist invisible between tags.

Look specifically at the tests for children and childNodes in the 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运行结果:");
 for(i = 0; i < child.length; i++){
   console.log(child[i].tagName);
  }
 
 console.log("");
 child = o.childNodes;
 console.log("div1.childNodes运行结果:");
 for(i = 0; i < child.length; i++){
   console.log(child[i].tagName);
  }
 
 }
 
 test();

</script>
</html>


The test results are as follows:

 div1.children运行结果:
 SPAN

 div1.childNodes运行结果:
 undefined
 SPAN
 undefined

There are two undefined nodes in the result of the childNodes collection above, and these two are TextNode with nodeType=3.

If the HTML code is written in the following style, there will be no difference in the results of children and childNodes.

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

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

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn