TheCarver
TheCarver

Reputation: 19733

jQuery/JS - Count elements within element

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

Upvotes: 2

Views: 21721

Answers (4)

Adrian
Adrian

Reputation: 23

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

Upvotes: -1

Diode
Diode

Reputation: 25165

var maindiv = document.getElementById('cont');
var count = maindiv.children.length;
alert(count);

Upvotes: 3

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

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.

Upvotes: 1

Jake Feasel
Jake Feasel

Reputation: 16945

console.log($("#cont div").length);

Upvotes: 5

Related Questions