Eric Eric - 6 months ago 14
Javascript Question

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....

Answer

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");
Comments