Reputation:
I want to show only 4 item and hide other items. how i can do it
$(".item").each(function(i, e){
if(i == 4 ){
$(this).addClass("hide");
}
})
Upvotes: 0
Views: 782
Reputation: 4814
As per syntax,
if you write i == 4
only at 4th loop it will hide.
you have to write i > 3
because array starts from zero(0), which will hide all after 4 items
$(".item").each(function(i, e){
if(i > 3){
$(this).addClass("hide");
}
})
Or simply you can do this:
$('.item').slice(3).addClass('hide')
Upvotes: 2
Reputation: 34556
You don't say if you want to show only the first four, or a particular four, but your code attempt suggests the former.
In which case, you don't need JavaScript at all - you can do it from CSS.
.item:nth-of-type(4) ~ .item { display: none; }
If for some reason you wish to do it with JS nonetheless, you could do:
$('.item:nth-child(4)').nextAll('.item').hide();
Upvotes: 0