Reputation: 35
I want to find in the div with the id CategoryBigContent all elements with the class .interestGrid and hide all elements except the first 4. I have already found the elements, but how can I add hidden only to all classes except the first four and not to all?
$('#CategoryBigContent).find('.interestGrid').addClass("hidden");
Upvotes: 1
Views: 1131
Reputation: 28196
John Resig put in so much effort into jQuery so many years ago and nobody seems to appreciate that. ;-)
The problem can be solved by simply using his :gt()
selector!
$('#CategoryBigContent .interestGrid:gt(3)').addClass("hidden");
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="CategoryBigContent">
<div class="interestGrid">1</div>
<div class="interestGrid">2</div>
<div class="interestGrid">3</div>
<div class="interestGrid">4</div>
<div class="interestGrid">5</div>
<div class="interestGrid">6</div>
</div>
Upvotes: 5
Reputation: 13222
You can use the filter function to filter by index.
$('#CategoryBigContent').find('.interestGrid').filter(function(index){
return index > 3;
}).addClass("hidden");
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="CategoryBigContent">
<div class="interestGrid">1</div>
<div class="interestGrid">2</div>
<div class="interestGrid">3</div>
<div class="interestGrid">4</div>
<div class="interestGrid">5</div>
<div class="interestGrid">6</div>
</div>
Upvotes: 3