Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 457
fearofawhackplanet Avatar asked Jul 26 '10 11:07

fearofawhackplanet


People also ask

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

What is a parent selector?

The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.

What is jQuery parent function?

The parent() is an inbuilt method in jQuery which is used to find the parent element related to the selected element. This parent() method in jQuery traverse a single level up the selected element and return that element. Syntax: $(selector).parent() Here selector is the selected elements whose parent need to find.


2 Answers

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

like image 87
Nick Craver Avatar answered Oct 07 '22 01:10

Nick Craver


$(element).parents('TR:first');

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

like image 42
Jason Avatar answered Oct 07 '22 02:10

Jason