2

In jQuery or JS I need to count the amount of DIV elements inside my parent DIV called cont? I've seen similar questions here on StackOverflow and have tried the following.

<div class="b-load" id="cont">
    <div>
    <img src="page2.jpg" alt=""/>
    </div>
    <div>
    <img src="page3.jpg" alt="" />
    </div>
    <div>
    <img src="page4.jpg" alt="" />
    </div>
    <div>
    <img src="page5.jpg" alt="" />
    </div>
</div>

function countPages() {
    var maindiv = document.getElementById('cont');
    var count = maindiv.getElementsByTagName('div').length;
    alert(count);
}

The child DIV's are dynamically produced, so I need to count them after the page has finished loading. The problem I have is the function I wrote counts 13 DIV's and in this example, there should only 4!! Any help gratefully received..

TheCarver
  • 19,391
  • 25
  • 99
  • 149

4 Answers4

5
console.log($("#cont div").length);
Jake Feasel
  • 16,785
  • 5
  • 53
  • 66
  • @ŠimeVidas: you are incorrect. If an #id is the first part of a selector, Jake's way is the fastest. Ref: http://stackoverflow.com/questions/2421782/performance-of-jquery-selector-with-context – Interrobang Dec 22 '11 at 01:53
  • @Interrobang That accepted answer in that thread shows that adding context improves performance. However, there is no mention of a `#foo div` selector in that question... – Šime Vidas Dec 22 '11 at 02:01
  • The accepted answer says that adding context improves performance except in the case of ID selectors, and a JSPerf link is provided in the thread as well. – Interrobang Dec 22 '11 at 02:07
3
var maindiv = document.getElementById('cont');
var count = maindiv.children.length;
alert(count);
Diode
  • 24,570
  • 8
  • 40
  • 51
1

Try this

$(function(){
   var mainDiv = $('#cont');
   var childDivCount = mainDiv.find('div').length;
   });

By the way, this is jQuery's syntax (one of them anyways) for document ready. This will only fire after your page has completed loading.

Bassam Mehanni
  • 14,796
  • 2
  • 33
  • 41
-1

No need to use jQuery here. If you only need to know the amount of childElements, you can use node.childElementCount

Adrian
  • 13
  • 4