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

4
  • 3
    it shows 4 correctly - jsfiddle.net/QSurJ Commented Dec 22, 2011 at 1:03
  • All I'm doing different is using [body onload="countPages()"] Commented Dec 22, 2011 at 1:07
  • I just changed getElementsByTagName('div') to getElementsByTagName('img') and I get the correct number but I'm still shocked that I get a different number than the fiddle example!! Commented Dec 22, 2011 at 1:12
  • maybe you have somewhere on your page a second element with id=cont ? Commented Dec 22, 2011 at 1:14

4 Answers 4

5
console.log($("#cont div").length);
Sign up to request clarification or add additional context in comments.

3 Comments

@ŠimeVidas: you are incorrect. If an #id is the first part of a selector, Jake's way is the fastest. Ref: stackoverflow.com/questions/2421782/…
@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...
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.
3
var maindiv = document.getElementById('cont');
var count = maindiv.children.length;
alert(count);

Comments

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.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.