A. Rossi A. Rossi - 6 months ago 28
jQuery Question

Jquery selector next element

Is there is a way to select every next element (nested or not) ?
Example :

<div class="div1">
<span class="span2">span1</span>

<div class="div2">
<span class="span2">span2</span>
</div>

<span id="current_span">current span></span>

<span class="span2">span3</span>

<div class="div2">
<span class="span2">span4</span>
</div>

</div>


I would like to do something like it :

$("#current_span").[select_every_next_item_with_span2_class].hide();


span3
/
span4
hidden

And

$("#current_span").[select_every_prev_item_with_span2_class].show();


span1
/
span2
visible

Answer

You could do this with jQuery's nextAll() and prevAll() functions.

For your code, this would be:

$("#current_span").nextAll().hide();
$("#current_span").prevAll().hide();

And as always, you can traverse the items in the list from the functions if you wish to do something separate with specific ones (i.e. use the each() function).

EDIT: If you want to select the child elements of the siblings as well, you can do:

$("#current_span").nextAll().children().andSelf().hide();

This selects both the siblings and the children of the siblings.

I also added a code snippet to show you how this can work with your code. Click on currentspan1 to toggle the top two elements and currentspan2 to toggle the bottom two.

$("#current_span1").click(function(){
  $(this).prevAll().toggle();
});

$("#current_span2").click(function(){
  $(this).nextAll().toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div1">
  <span class="span2">span1</span>

  <div class="div2">
    <span class="span2">span2</span>
  </div>

  <span id="current_span1">current span1</span> <br>
  <span id="current_span2">current span2</span> <br>

  <span class="span2">span3</span>

  <div class="div2">
    <span class="span2">span4</span>
  </div>
</div>