Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

dom - Javascript - child node count

<ul>
    <li>Array1</li>
    <li>Array2</li>
    <li id="element">Array3</li>
</ul>
<script>
   var temp = document.getElementById('element').parentNode;
   child = temp.childNodes;
   console.log(temp.length);
</script>

I need to get the child node length using element id. My code returns 7 as a result but I have only 3 nodes.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

childNodes gets all existing childNodes, including text nodes! In your example markup, you have your three "regular nodes" and 4 text nodes - the linebreaks - resulting in a total of 7 child nodes.

What you instead want is .children.length or .childElementCount (not supported in IE<9) to only fetch "actual" nodes:

let temp = document.getElementById('element').parentNode;
console.log(temp.children.length);
// or the following
console.log(temp.childElementCount);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...