Look for similar questions I found this question and this other question
But this does not work for me when I have the same container to which I want to count the articles that each container has, for example:
<div id="slider">
<button class="btn"></button>
<button class="btn"></button>
<div class="slider">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
<div id="slider">
<button class="btn"></button>
<button class="btn"></button>
<div class="slider">
<div class="item"></div>
<div class="item"></div>
</div>
</div>
What I need is to be able to hide the buttons that have less than or equal to 4 articles (<div class="item"></div>
), I have tried the following, but it hides all the buttons even those that have more than 5 articles (<div class="item"></div>
).
$(".slider").each(function(){
var numItems = $(this).find("div.item").length;
if (numItems <= 4) {
$('button.btn').css('display','none');
}
});
What changes do I need to make to make it work properly?
CodePudding user response:
$('button.btn').css('display','none');
will hide all buttons. To hide just the buttons inside the sliders with 4 or fewer articles, try:
$(this).find('button.btn').css('display','none');
Explanation: $(this)
starts at the slider you're up to in the .each()
loop. Then, .find('button.btn')
finds just the buttons that are descendants of that particular slider.