Mohammad Rayan Mohammad Rayan - 7 months ago 11
Javascript Question

select the first matching down the tree among sibling divs using JQuery

Suppose I have

<div class="x">
<div class="y"></div>
<div class="y"></div>
<div class="y"></div>
<div class="y"></div>
<div class="y"></div>
<div class="y"></div>
<div class="z"></div>
<div class="y"></div>
<div class="y"></div>
<div class="y"></div>
<div class="z"></div>
</div>


On Click of .y I need to select .z which is first one down the order.
What should I write after

$(this). ?


where this is the div I have clicked.

Answer

Use jQuery's nextAll and first functions:

var z = $(this).nextAll('.z').first();

Learn more:

https://api.jquery.com/nextAll/

https://api.jquery.com/first/