Eric
Eric

Reputation: 5215

jQuery - how to find element inside following child?

I need the jQuery statement to find ".findme" in this code:

$('.clicky').click(function() {
    // the .find() method doesn't do it
    $(this).find('.findme').css('color', 'red');
});

<div class='clicky'></div>
<div class='brother'>
    <div class='findme'>Here I am</div>
</div>

I've tried variations on .find() and .next() and .children() and I can't quite work it out....

Upvotes: 0

Views: 73

Answers (2)

user1937699
user1937699

Reputation:

you may can try to change

$('.clicky').click(function() {
    // the .find() method doesn't do it
   $(this).siblings().children('.findme').css('color', 'red');
});

and i think you miss the click me inner text for the div

<div class='clicky'>click me!!!</div>
<div class='brother'>
  <div class='findme'>Here I am</div>
</div>

Upvotes: 1

Joel
Joel

Reputation: 2257

this in $(this).find('.findme') actually refers to the element that was clicked (the div with the class clicky.

.find() actually searches the descendants of the element you call it on, and since "findme" is not within the "clicky" div, it doesn't find it.

You should instead use jquery's .next() function to get the sibling immediately following the "clicky" div (that's the "brother"), and then search there for the "findme" div.

$(this).next().find(".findme").css("color", "red");

Upvotes: 2

Related Questions