How to get the next element that appears in jquery

I have some elements from both the previous and next links in each of these elements. As if I click on next, I want to add the class only to the next div that is visible, and I want to skip the hidden divs and if the div is hidden, add the class to the next div that will be visible after the hidden element. for this i wrote something like this

$('.next').click(function(){ $('.slide').removeClass('highZindex'); $(this).closest('.slide').next('.slide:visible').addClass('highZindex') }) 

I just want to remove the added class from all of these elements and just add to the next visible element, but what happens if I click on the next link and if the next div is hidden, it skips all the elements and goes directly to the last div and the class also doesn't add to which element.

 $('.slide').first().addClass('highZindex'); $('.prev').click(function(){ $('.slide').removeClass('highZindex'); $(this).closest('.slide').prev('.slide:visible').addClass('highZindex') }) $('.next').click(function(){ $('.slide').removeClass('highZindex'); $(this).closest('.slide').next('.slide:visible').addClass('highZindex') }) 
 .slide {border:1px solid; height:200px; width:200px;position:absolute;top:0px; left:0px; background-color:#fff; } .highZindex {z-index:1000} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="slide">1 <a href="#" class="prev">prev</a> <a href="#" class="next">next</a></div> <div class="slide">2 <a href="#" class="prev">prev</a> <a href="#" class="next">next</a></div> <div class="slide">3 <a href="#" class="prev">prev</a> <a href="#" class="next">next</a></div> <div class="slide" style="display:none;">4 <a href="#" class="prev">prev</a> <a href="#" class="next">.next</a></div> <div class="slide">5 <a href="#" class="prev">prev</a> <a href="#" class="next">next</a></div> <div class="slide">6 <a href="#" class="prev">prev</a> <a href="#" class="next">next</a></div> <div class="slide">7 <a href="#" class="prev">prev</a> <a href="#" class="next">next</a></div> 
+5
source share
1 answer

Just go from prev '/' next 'to' prevAll '/' nextAll 'and select the first item from the list.

Modified Rows

 $(this).closest('.slide').prevAll('.slide:visible').first().addClass('highZindex'); $(this).closest('.slide').nextAll('.slide:visible').first().addClass('highZindex'); 

If you do not want to use looping prev btn, you can add a condition:

 $('.prev').click(function(){ if(!($(this).closest('.slide').prevAll('.slide:visible').length == 0)) { $('.slide').removeClass('highZindex'); $(this).closest('.slide').prevAll('.slide:visible').first().addClass('highZindex'); } }) 
+3
source

All Articles