Mohammad Rayan
Mohammad Rayan

Reputation: 312

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.

Upvotes: 1

Views: 41

Answers (3)

S.W.
S.W.

Reputation: 68

.next() will select from the tree downwards, .closest() will search for closest ancestors, try:

$(this).next("div.z");

Upvotes: 0

smaili
smaili

Reputation: 1235

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/

Upvotes: 3

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

You can use nextAll() method like following.

$(this).nextAll('.z:first')

Upvotes: 3

Related Questions