Search code examples
javascripthtmlchildrengetelementsbytagname

Get count of direct children of specific type from div


Im new to javascript and im trying to get a count of how many paragraphs each div has as direct children.

Example:

<div id="1">
    <p>text</p>
    <p>text</p>
    <div id="2">
        <p>text</p>
    </div>
</div>
<div id="3">
    <p>text</p>
    <p>text</p>
    <p>text</p>
</div>

The result im looking for:

  • div 1 = 2
  • div 2 = 1
  • div 3 = 3

The code that i got so far looks like this:

var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++){
    var count = divs[i].getElementsByTagName('p').childElementCount;
    console.log('div ' + i + ' count ' + count);
}

The result:

Console log

Why do i get "undefined"? tried using .length instead of .childElementCount but that did not give me the desired result either.

Struggling to find a solution for this myself, jquery is not an option.


Solution

  • var divs = document.getElementsByTagName('div');
    for (var i = 0; i < divs.length; i++) {
      var count = divs[i].querySelectorAll(':scope > p').length;
      console.log('div ' + i + ' count ' + count);
    }
    <div id="1">
      <p>text</p>
      <p>text</p>
      <div id="2">
        <p>text</p>
      </div>
    </div>
    <div id="3">
      <p>text</p>
      <p>text</p>
      <p>text</p>
    </div>

    :scope means the parent element itself. > means to select the direct/immediate children.

    Check out how :scope pseudo-class is currently supported here. No support from IE, but there is a shim available.