Xtatic Uforia
Xtatic Uforia

Reputation: 99

jQuery Closest() isn't working

Could someone please explain me why replacing the following

$('.post_title a').hover(function () {
    $(this).parent().parent().parent().parent().find(".post_footer").toggleClass('footer_border')
});

with

$('.post_title a').hover(function () {
    $(this).closest(".post_footer").toggleClass('footer_border')
});

doesn't work??

Upvotes: 4

Views: 10469

Answers (3)

King Friday
King Friday

Reputation: 26076

Try doing this...

$('.post_title a').hover(function () {
    $(this).closest(PARENT_OF_POST_FOOTER_SELECTOR)
        .find(".post_footer").toggleClass('footer_border')
});

This assumes you have defined PARENT_OF_POST_FOOTER_SELECTOR.

Upvotes: 0

Ry-
Ry-

Reputation: 224922

Look at the documentation for .closest(). It states that:

Given a jQuery object that represents a set of DOM elements, the .closest() method searches through these elements and their ancestors in the DOM tree and constructs a new jQuery object from the matching elements. The .parents() and .closest() methods are similar in that they both traverse up the DOM tree.

Since the element you're looking for isn't an ancestor of your link, it won't work. To achieve what you need, you could use this instead:

$(this).parents().next('.post_footer').eq(0).toggleClass('footer_border');

Upvotes: 7

Rory McCrossan
Rory McCrossan

Reputation: 337560

closest() is used to find the closest direct parent of an element.

In your first example, you use find() to locate an element inside the parent of the current element. This is why closest() fails - .post_footer is not a direct parent of the current element.

If you could post the HTML structure of your code I could provide you with more detail on how to resolve this.

Upvotes: 3

Related Questions