4

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

Esailija
  • 138,174
  • 23
  • 272
  • 326
Xtatic Uforia
  • 99
  • 1
  • 1
  • 7
  • Is `.post_footer` exists inside `.post_title a`? `.closest()` searches current item and its parents. – biziclop Jan 08 '12 at 16:41
  • 3
    Probably because `.post_footer` is not an ancestor of `a`. If you'd post your HTML we could say more. – Felix Kling Jan 08 '12 at 16:42
  • Please post your HTML. ALL answers would have to be guesses or inferences about what your HTML must look like as that is what determines how you find other objects in the page. – jfriend00 Jan 08 '12 at 16:45

3 Answers3

7

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');
Ry-
  • 218,210
  • 55
  • 464
  • 476
3

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.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

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.

King Friday
  • 25,132
  • 12
  • 90
  • 84