2015-02-05 163 views
2

嘿,我需要用給定的類名稱來計算嵌套的div。例如:在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> 

所以,如果我想要數「toBeCounted」,我會得到3的divA和2的divB。

回答

6

您可以使用.querySelectorAll()和檢查結果的長度:

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

>關係堅持認爲,.toBeCounted元素是​​直接孩子。如果這不是你想要的,並且​​內的任何toBeCounted div應該算在內,那麼你只需要省略>

+0

這假設OP沒有針對IE瀏覽器<8(並且希望他們不是) – 2015-02-05 16:01:55

+1

@ElGuapo是的,這是真的 - 這是我的項目的一部分,讓IE8走出去,讓世界相信它可以' t可能是真實的 – Pointy 2015-02-05 16:04:26

+0

HAHAHAHAHAHAHAHAHAHAHAHA – 2015-02-05 16:59:02

1

與jQuery這可以通過使用

var countA = $("#divA .toBeCounted").length; 
var countB = $("#divB .toBeCounted").length; 
1

可以輕鬆實現試試這個純JavaScript代碼

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

如果你不事先知道父母的ID的,這可能證明有用:

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 ]