Reputation: 1557
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
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
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
Reputation: 14456
$('.container').each(function(i, obj){
var children = $(this).find('.child').length;
$('<p>' + children + ' elements.</p>').appendTo( $(this) );
});
Upvotes: 2
Reputation: 194
use .length to get count of its source
example...
alert($('.container').children().length);
Upvotes: 2