Home > Web Front-end > JS Tutorial > 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
Release: 2016-05-16 16:06:38
Original
1246 people have browsed it

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>

Copy after login


The test results are as follows:

 div1.children运行结果:
 SPAN

 div1.childNodes运行结果:
 undefined
 SPAN
 undefined

Copy after login

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>

Copy after login

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

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template