Hey I need to count the nested divs with a given class name. For example:
<div id = "divA">
<div class = "anotherName"></div>
<div class = "toBeCounted"></div>
<div class = "someName"></div>
<div class = "toBeCounted"></div>
<div class = "toBeCounted"></div>
<div class = ""></div>
</div>
<div id = "divB">
<div class = ""></div>
<div class = "toBeCounted"></div>
<div class = ""></div>
<div class = "toBeCounted"></div>
</div>
So if I want to count "toBeCounted" I would get 3 for divA and 2 for divB.
Hey I need to count the nested divs with a given class name. For example:
<div id = "divA">
<div class = "anotherName"></div>
<div class = "toBeCounted"></div>
<div class = "someName"></div>
<div class = "toBeCounted"></div>
<div class = "toBeCounted"></div>
<div class = ""></div>
</div>
<div id = "divB">
<div class = ""></div>
<div class = "toBeCounted"></div>
<div class = ""></div>
<div class = "toBeCounted"></div>
</div>
So if I want to count "toBeCounted" I would get 3 for divA and 2 for divB.
Share Improve this question asked Feb 5, 2015 at 15:48 Svetoslav PetrovSvetoslav Petrov 1,1981 gold badge14 silver badges33 bronze badges4 Answers
Reset to default 7You can use .querySelectorAll()
and check the length of the result:
var divAcount = document.querySelectorAll("#divA > .toBeCounted").length;
The >
relation insists that the .toBeCounted
elements are immediate children of divA
. If that's not what you want, and any toBeCounted
div within divA
should count, you'd just leave out the >
.
try this pure javascript code
var countinDivA = document.getElementById("divA").getElementsByClassName("toBeCounted").length;
var countinDivB = document.getElementById("divB").getElementsByClassName("toBeCounted").length;
With Jquery this can be easily achieved by using
var countA = $("#divA .toBeCounted").length;
var countB = $("#divB .toBeCounted").length;
If you don't know the id's of the parents ahead of time, this may prove useful:
var parents = [],
counted = document.getElementsByClassName("toBeCounted");
for (var i=0; i < counted.length; i++ ) {
var id = counted[i].parentNode.id;
if ( !parents[id] ) parents[id] = 1
else parents[id]++;
}
[ divA: 3, divB: 2 ]