jQuery Closest() isn't working

Xtatic Uforia picture Xtatic Uforia · Jan 8, 2012 · Viewed 8.9k times · Source

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

Answer

Ry- picture Ry- · Jan 8, 2012

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');