Count immediate child div elements using jQuery

后端 未结 12 2060
无人共我
无人共我 2020-11-28 01:19

I have the following HTML node structure:

<
相关标签:
12条回答
  • 2020-11-28 01:46

    Try this for immediate child elements of type div

    $("#foo > div")[0].children.length
    
    0 讨论(0)
  • 2020-11-28 01:48

    In response to mrCoders answer using jsperf why not just use the dom node ?

    var $foo = $('#foo');
    var count = $foo[0].childElementCount
    

    You can try the test here: http://jsperf.com/jquery-child-ele-size/7

    This method gets 46,095 op/s while the other methods at best 2000 op/s

    0 讨论(0)
  • 2020-11-28 01:52
    $("#foo > div") 
    

    selects all divs that are immediate descendants of #foo
    once you have the set of children you can either use the size function:

    $("#foo > div").size()
    

    or you can use

    $("#foo > div").length
    

    Both will return you the same result

    0 讨论(0)
  • 2020-11-28 01:52
    var divss = 0;
    $(function(){
       $("#foo div").each(function(){
        divss++;
    
       });
       console.log(divss);  
    });     
    <div id="foo">
      <div id="bar" class="1"></div>
      <div id="baz" class="1"></div>
      <div id="bam" class="1"></div>
    </div>
    
    0 讨论(0)
  • 2020-11-28 01:56

    I recommend using $('#foo').children().size() for better performance.

    I've created a jsperf test to see the speed difference and the children() method beaten the child selector (#foo > div) approach by at least 60% in Chrome (canary build v15) 20-30% in Firefox (v4).

    By the way, needless to say, these two approaches produce same results (in this case, 1000).

    [Update] I've updated the test to include the size() vs length test, and they doesn't make much difference (result: length usage is slightly faster (2%) than size())

    [Update] Due to the incorrect markup seen in the OP (before 'markup validated' update by me), both $("#foo > div").length & $('#foo').children().length resulted the same (jsfiddle). But for correct answer to get ONLY 'div' children, one SHOULD use child selector for correct & better performance

    0 讨论(0)
  • 2020-11-28 02:02
    var n_numTabs = $("#superpics div").size();
    

    or

    var n_numTabs = $("#superpics div").length;
    

    As was already said, both return the same result.
    But the size() function is more jQuery "P.C".
    I had a similar problem with my page.
    For now on, just omit the > and it should work fine.

    0 讨论(0)
提交回复
热议问题