Reputation: 13843
I have the following output:
<section class="group">
<div class="header">Header 1</div>
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
</div>
</section>
<section class="group">
<div class="header">Header 2</div>
<div class="item">item1</div>
<div class="item">item2</div>
<div class="item">item3</div>
<div class="item">item4</div>
<div class="item">item5</div>
</div>
</section>
I want to use jQuery to tell me how many .item
elements are in each <section>
. Currently trying this, but it doesn't give me the correct number:
$('section.group').each(
function() {
alert($(this).length);
}
);
Upvotes: 3
Views: 23014
Reputation: 1329
$(".group").find(".item").length
This is the simplest one line solution.
Upvotes: 2
Reputation: 1745
try this.
$('.change').click(function () {
var lng = $(".item").length;
$('.change ').height(function (index, height) {
return (height * lng);
//alert(height);
});
alert(lng);
});
.change is the class of div which height or width you have t o change you can check how to implement here : http://jsfiddle.net/sahilosheal/572WV/
Upvotes: 1
Reputation: 355
I have change the name of second section class name see demo here:
$('section').each(function() {
var numItems = $('.group').children('div.item').length;
alert(numItems+'');
});
$('section').each(function() {
var numItems = $('.group1').children('div.item').length;
alert(numItems+'');
});
See this demo.
Upvotes: 0
Reputation: 1239
$('section.group').each(
function() {
alert($(this).children('.item').length);
}
);
this would be faster than the other ones....I suppose
Upvotes: 1
Reputation: 382656
Try:
$('section.group').each(
function() {
alert($('.item', $(this)).length);
}
);
Or
$('section.group').each(
function() {
alert(($(this).find('.item')).length);
}
);
You were iterating over sections but you were missing to count elements with class item
:)
Helpful Links:
Upvotes: 15
Reputation: 26320
Look the following example. http://jsfiddle.net/ricardolohmann/KMgtZ/
Upvotes: 1
Reputation: 11552
Try this instead:
$('section').each(function() {
alert($('.item', this).length);
});
Demo: http://jsfiddle.net/aXVqM/
Upvotes: 1
Reputation: 5511
You need to look at '.item' in the context of this. this has a length of one because this = 'section.group'
$('section.group').each(
function() {
alert($('.item',this).length);
}
);
See the Selector Context heading here: http://api.jquery.com/jQuery/
Upvotes: 1