2010-11-27 49 views
261

jQueryの子要素の数

<div id="selected"> 
 
    <ul> 
 
    <li>29</li> 
 
    <li>16</li> 
 
    <li>5</li> 
 
    <li>8</li> 
 
    <li>10</li> 
 
    <li>7</li> 
 
    </ul> 
 
</div>

<div id="selected"></div><li>要素の合計数を数えたいと思います。どのようにjQueryの.children([selector])を使用して可能ですか?

+0

http://stackoverflow.com/questions/250688/count-で簡単に可能ですdiv-elements-using-jquery – onder

答えて

13
var length = $('#selected ul').children('li').length 
// or the same: 
var length = $('#selected ul > li').length 

子セレクタでは、おそらくliを省略することもできます。

.lengthを参照してください。

10
$('#selected ul').children().length; 

またはより良い

$('#selected li').length; 
17

1最速:

$("div#selected ul li").length 
+1

これは最速ではありませんが、実際にはそこにdivを追加することで速度が遅くなります:) –

+2

それを試して時間を比較してください –

+1

本当にどちらの眉に依存しますかあなたは使っています。現代の多くのブラウザでは、要素を追加すると、idやクラスで見つける前にfindByElementを使用しますが、これは遅いです。まもなく、どちらの方法でも問題はありません。すべてのDOM検索は、1つのネイティブ関数を使用して行われるためです。 いずれの場合でも、単純なgetElementById( 'selected')または$( 'selected')はこの時点でより高速になります。 –

25
$("#selected > ul > li").size() 

か:

$("#selected > ul > li").length 
+7

ちょうどメモ.size()の代わりに.lengthが使用されています –

11

あなたはJavaScrを使用することができますIPT(jQueryの必要はありません)

document.querySelectorAll('#selected li').length; 
2

それは純粋なJavaScriptでchildElementCount

var countItems = document.getElementsByTagName("ul")[0].childElementCount; 
 
console.log(countItems);
<div id="selected"> 
 
    <ul> 
 
    <li>29</li> 
 
    <li>16</li> 
 
    <li>5</li> 
 
    <li>8</li> 
 
    <li>10</li> 
 
    <li>7</li> 
 
    </ul> 
 
</div>