最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Count nested divs in JavaScript - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

4 Answers 4

Reset to default 7

You 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 ]
发布评论

评论列表(0)

  1. 暂无评论