Search code examples
jquerydomjquery-selectorsdom-traversal

jQuery parent selectors


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.


Solution

  • 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