jQuery parent selectors
Asked Answered
R

3

5

Is there a jQuery parent selector that traverses up the DOM until the first match is found?

Eg:

<tr>
    <td>
        <div id="foo">hello!</div>
    </td>
</tr>

to find the row from the div I am using:

$('#foo').parent().parent();

It feels like I should be able to write something like

$('#foo').firstParent('tr');

but I can't find any such function in the docs.

Retrorocket answered 26/7, 2010 at 11:25 Comment(0)
L
6

You can use .closest() for this:

$('#foo').closest('tr');

If it helps, there's a category specifically for this to narrow your future searches to: Tree Traversal

Luba answered 26/7, 2010 at 11:29 Comment(2)
Thanks and cheers for the tree traversal link. I would never have found that, seems a pretty badly named function imho.Retrorocket
@Retrorocket - When you search the API: api.jquery.com find a function you know to be in the same area, and on the right it'll have links to the categories it belongs to, that's usually the quickest route :)Luba
C
1
$(element).parents('TR:first');

Edit: Or what Nick said below - forgot about that sucker.

Chinua answered 26/7, 2010 at 11:30 Comment(1)
+1 - This is the long-hand equivalent of .closest('tr') so certainly a valid approach :)Luba
J
0
$('#foo').parent('tr')
Jorum answered 26/7, 2010 at 11:32 Comment(1)
This doesn't behave like most people expect, it selects the parent if it's a <tr>, if it's not a <tr> you get an empty set. The selector is a filter, rather than a search term, it's equivalent to .parent().filter('tr') for that step :)Luba

© 2022 - 2024 — McMap. All rights reserved.