Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery parent of a parent

I am currently trying to find the parent of a parent of an element. I have a link being clicked that is in a <td>, and I'd like to get the <tr> object.

Why wont "$(this).parent().parent()" work? What will?

Thanks,
Brendan

Edit: It appears an error in my syntax was throwing the whole thing off. "$(this).parent().parent()" does in fact work, but I wound up going with $(this).closest('tr')" because it seems like the most efficient solution.

like image 676
bloudermilk Avatar asked Jun 08 '09 19:06

bloudermilk


People also ask

What is this parent parent in jQuery?

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. Here selector is the selected elements whose parent need to find.

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 the use of parent () and child () method in jQuery?

It is a jQuery Selector used to select all elements that are the direct child of its parent element. Parameter Values: parent: Using this, the parent element will be selected. child: Using this, the direct child element of the specified parent element will be selected.


2 Answers

The best way would probably be using closest:

$(this).closest('tr'); 

Check out the documentation:

Closest works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the specified expression. If no matching element is found then none will be returned.

like image 191
Paolo Bergantino Avatar answered Oct 14 '22 01:10

Paolo Bergantino


It should work. You can also try $(this).parents(tag) , where tag is the tag you want to find.

For example:

$(this).parents("tr:first") 

Will find the closest tr "up the chain".

like image 20
Philippe Leybaert Avatar answered Oct 14 '22 00:10

Philippe Leybaert