views:

39

answers:

3

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.

+4  A: 

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

Nick Craver
Thanks and cheers for the tree traversal link. I would never have found that, seems a pretty badly named function imho.
fearofawhackplanet
@patrick - Woops, thanks!
Nick Craver
@fearofawhackplanet - When you search the API: http://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 :)
Nick Craver
+1  A: 
$(element).parents('TR:first');

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

Jason
+1 - This is the long-hand equivalent of `.closest('tr')` so certainly a valid approach :)
Nick Craver
A: 
$('#foo').parent('tr')
Zane Edward Dockery
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 :)
Nick Craver