I have the following example structure where there are some groups with different headerx
class but same class at the group
and at the groupxbottom
, and unknown number of <li>
s between them.
I get all the headers with specific headerx
class:
let headers = $('.header1');
Then I need to hide the matching groupxbottom
for each group.
I have the selector that matches groupxbottom
using match()
. The problem is that it matches all groupxbottom
elements, but I only need to select 1 groupxbottom
which is the next closest sibling.
Assuming I already extract the correct class name and it’s saved in selector
, how can I match it with the next closest sibling while iterating headers:
headers.each(function() {
$(this).(.. use selector for next closest sibling only ..).hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<li class="header1 group1">Header1 Group1</li>
<li class="group1"></li>
<li class="group1"></li>
<li class="group1"></li>
<li class="group1"></li>
<li class="group1"></li>
<li class="group1bottom">Group 1 bottom</li>
<li class="header1 group2">Header1 Group2</li>
<li class="group2"></li>
<li class="group2"></li>
<li class="group2bottom">Group2 bottom</li>
<li class="header2 group1">Header2 Group1</li>
<li class="group1"></li>
<li class="group1"></li>
<li class="group1bottom">Group1 bottom</li>
2
Answers
Use
siblings()
https://api.jquery.com/siblings/jQuery’s
nextAll()
, along with a partial attribute selector, can find the group elements. Then we just grab the first one in the set.Note that it’s not necessary to use distinct class names. They can all be the same.