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:
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:
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.
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.