Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
661 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 Answer

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...