在JavaScript中计算嵌套的div

时间:2015-02-05 15:48:08

标签: javascript

嘿我需要用给定的类名来计算嵌套的div。例如:

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

所以,如果我想计算&#34; toBeCounted&#34;我会为divA获得3,为divB获得2。

4 个答案:

答案 0 :(得分:7)

您可以使用.querySelectorAll()并检查结果的长度:

var divAcount = document.querySelectorAll("#divA > .toBeCounted").length;

>关系坚持.toBeCounted元素是divA的直接子元素。如果那不是您想要的,并且toBeCounted中的 divA div应该计算在内,那么您只需忽略>

答案 1 :(得分:1)

使用Jquery,可以使用

轻松实现
var countA = $("#divA .toBeCounted").length;
var countB = $("#divB .toBeCounted").length;

答案 2 :(得分:1)

试试这个纯粹的javascript代码

var countinDivA = document.getElementById("divA").getElementsByClassName("toBeCounted").length;
var countinDivB = document.getElementById("divB").getElementsByClassName("toBeCounted").length;

答案 3 :(得分:1)

如果您不提前知道父母的身份证明,这可能会有用:

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 ]