Skip to content Skip to sidebar Skip to footer

Counting Divs Inside Div

i have tried the solutions on this page for counting divs inside parent (class) div. but unfortunately my result is alway displaying the whole number of existing children divs. as

Solution 1:

Check this fiddle: http://jsfiddle.net/geko/vXcgZ/

Problem is your each, and the

$('.detail').children('.box').length

This selects all .detail elements in your container and all children with .box. Which is a total of 7. You should go through .detail using each() and take count for .box children and modify coresponding countDiv.

Solution 2:

I don't know why you are trying to count the divs with the same class name. When you are using $('.detail') it will get all the elements which have the class name "detail" in the page, so you cannot count the specific div with the same name with other divs by this way.

$('#content-body').each(function() { 
      var n = $('.detail').children('.box').length;
      $(".countDiv").text("There are " + n + " divs inside parent box detail.");
});

I think it could be:

$('#content-body .detail').each(function() { 
      var n = $(this).children('.box').length;
      $(this).append("<div>There are " + n + " divs inside parent box detail.</div>");
});

and if you want to count the specific div you should provide different class name.

Post a Comment for "Counting Divs Inside Div"