Home > Net >  Count specific elements in a div container on the top level only
Count specific elements in a div container on the top level only

Time:12-10

My HTML Structure is like this:

<div container>
    <div child_container>
        <span 1> 1 </span>
        <span 2> 2 </span>
    </div child_container>>
    <span 3> 3 </span> 
    <span 4> 4 </span>
</div container>

I want to count the span 3 and span 4 inside my container. Not the spans inside the child_container.

I have tried several things:

This will count everything inside container:

var countElementsAfter = columnNamesOverview_comparison_values.getElementsByTagName("span").length; 

This wont work:

var countElementsAfter = columnNamesOverview_comparison_values.getElementsByTagName("span").childNodes[0]length;

And this, result is still 1, although I have two elements:

var countElementsAfter1 = columnNamesOverview_comparison_values.getElementsByTagName("span");
var k = [];
for (var i=0, len=c.length; i<len;   i) {
    k[k.length] = c[i];
    }

How can I count the span elements in my container without counting the child elements?

CodePudding user response:

You can use document.querySelectorAll which can use css selector

const spans = document.querySelectorAll("#container > span")
console.log(spans.length)
<div id="container">
    <div id="child_container">
        <span 1> 1 </span>
        <span 2> 2 </span>
    </div>
    <span 3> 3 </span> 
    <span 4> 4 </span>
</div>

in case you can't have a selector for the parent element (and thus, can't select it's child specifically), you can loop over it's children and filter

const container = document.querySelector("#container")
const spans = Array.from(container.children)
  .filter(child => child.tagName === "SPAN")
console.log(spans.length)
<div id="container">
    <div id="child_container">
        <span 1> 1 </span>
        <span 2> 2 </span>
    </div>
    <span 3> 3 </span> 
    <span 4> 4 </span>
</div>

  • Related