Mahdi
Mahdi

Reputation: 9417

first element after the clicked element

How do I get the first element which has an specific class, right after the clicked element.

<div class="box"></div>
<div class="box"></div>
<div class="box-data"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box-data"></div>

Here is my not-working solution:

$(".box").click(function() {
    $(":first .box-data").css("display", "block");
    //$(this).find(":first .box-data").css("display", "block");
});

The box-data is not visible by default, however by the above code both of them will be visible, unfortunately!

P.S. display: none; has been defined in box-data class.

Upvotes: 1

Views: 738

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074258

Using nextAll(".box-data") and first():

$(".box").click(function() {
    $(this).nextAll(".box-data").first().css("display", "block");
});

nextAll returns the following siblings in order, and first chooses just the first of them (first = eq(0)).

Upvotes: 2

Related Questions