alexx0186
alexx0186

Reputation: 1557

How to count div's of one class, that are children of container div's of one class?

I would like to count the number of ('.child') in each container and append a sentence with the count inside each container.

<div class='container'>
     <div class='child'></div>
     <div class='child'></div>
     <div class='child'></div>
     <div class='child'></div>
</div>

<div class='container'>
     <div class='child'></div>
     <div class='child'></div>
</div>

How would you do that? Would you need id's or can it be done with just classes? I want to find a clean way of doing it. Thanks a lot in advance

Upvotes: 0

Views: 897

Answers (4)

faino
faino

Reputation: 3224

Here is a simple example that should handle what you are looking for

jQuery

<script>
    $(function(){
        $('.container').each(function(){
            var count=0,child=$(this).find('.child');
            if(child.length>0) {
                count++;
                child.each(function(){
                    $(this).text('This is child number '+count);
                    count++;
                });
            }
        });
    });
</script>

HTML

<div class="container">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>
<div class="container">
    <div class="child"></div>
    <div class="child"></div>
</div>

Upvotes: 1

sakhunzai
sakhunzai

Reputation: 14470

check this fiddle

You don't need additional thing give the above html structure

  $('.container').each(function(){

    $(this).prepend('<label> No of children:'
                    +$(this).find('div.child').size()
                    +'</label>');
  });

Upvotes: 1

Kevin Ennis
Kevin Ennis

Reputation: 14456

$('.container').each(function(i, obj){
    var children = $(this).find('.child').length;
    $('<p>' + children + ' elements.</p>').appendTo( $(this) );
});

Upvotes: 2

Dasarp
Dasarp

Reputation: 194

use .length to get count of its source

example...

alert($('.container').children().length);

Upvotes: 2

Related Questions