jQuery Minute™

…a jQuery Minute™ later and you're done!



jQuery parent() vs. parents()

with 7 comments

Welcome jQuery newbies! I’m writing a quick post here to help clarify some differences between the parent() and parents() methods.

Given the following HTML:
<html>…<body><div class=”one”><div class=”two”><p><span>Some text</span></p></div></div></body></html>

$(‘span’).parent() will select the <p> tag such that the element set in the jQuery object is [span].

$(‘span’).parents() will select all parent tags such that the element set in the jQuery object is [p, div.two, div.one, body, html].

So parent() will select the first parent element while parents() will select all elements straight up the DOM tree.

Now jQuery has some great flexibility in that you could do that following:

$(‘span’).parents().filter(‘div’) which would result in [div.two, div.one]. jQuery makes it even easier as the parent() and parents() methods support filtering built in so the above can be reduced to:

$(‘span’).parents(‘div’) giving you [div.two, div.one].

Let’s continue with one more example, let’s say that you only need the first div in the parent DOM tree, jQuery to the rescue $(‘span’).parents(‘div:eq(0)’) will give you [div.two]

-Jonathan

Written by jdsharp

January 24th, 2008 at 10:34 am

7 Responses to 'jQuery parent() vs. parents()'

Subscribe to comments with RSS or TrackBack to 'jQuery parent() vs. parents()'.

  1. Thanks. nice

    Rijas PA

    30 Nov 09 at 5:45 am

  2. salute

    Sap

    15 Dec 09 at 9:20 am

  3. thanks for this tip

    Dave Kiss

    15 Dec 09 at 10:44 pm

  4. Great!!!!!!!!!!! Very helpful explanation

    pnina

    18 Dec 09 at 5:13 am

  5. that was very helpful!!! thanks!!!

    php thumbnailer

    3 Jan 10 at 6:14 pm

  6. It’s awesome!!! Thanks a lot :P

    thinklinux

    14 Jan 10 at 9:34 am

  7. Your code works great, but I want to do one small thing that I can’t get to work. I want the click event to be on an ‘anchor’ tag inside of the ‘td’. So to reference the ‘td’ in the fnGetPosition function I would reference $(this).parent() to get the ‘td’. this doesn’t appear to be working for me. I know I’m doing something wrong, but I just don’t know what. Any help would be great. BTW, my code works your way just fine, so it can’t be much else.

    rich

    3 Feb 10 at 11:36 am

Leave a Reply