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.
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.
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.
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.
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
$(element).parents('TR:first');
Edit: Or what Nick said below - forgot about that sucker.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With