Search code examples
javascriptjqueryhtmldom-traversal

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.


Solution

  • 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/