Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a jQuery selector/method to find a specific parent element n levels up?

Consider the following HTML. If I have a JSON reference to the <button> element, how can I get a reference to the outer <tr> element in both cases

<table id="my-table">     <tr>         <td>             <button>Foo</button>         </td>         <td>             <div>                 <button>Bar</button>             </div>         </td>     </tr> </table>  <script type="text/js">     $('#table button').click(function(){         //$(this).parent().parent() will work for the first row         //$(this).parent().parent().parent() will work for the second row         //is there a selector or some magic json one liner that will climb         //the DOM tree until it hits a TR, or do I have to code this myself         //each time?                     //$(this).????     }); </script> 

I know I could special case each condition, but I'm more interested "however deep you happen to be, climb the tree until you find element X" style solution. Something like this, but more jQuery like/less-verbose

var climb = function(node, str_rule){     if($(node).is(str_rule)){         return node;     }     else if($(node).is('body')){         return false;     }     else{         return climb(node.parentNode, str_rule);     } };   

I know about the parent(expr) method, but from what I've seen is allows you filter parents one level up and NOT climb the tree until you find expr (I'd love code example proving me wrong)

like image 689
Alan Storm Avatar asked Mar 30 '09 21:03

Alan Storm


People also ask

How do I find a specific parent in jQuery?

jQuery parent() Method 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.

How do you find the parent element?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.

What is the difference between parent () and parents () methods in jQuery?

parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree. parents() method allows us to search through the ancestors of these elements in the DOM tree.

Which is the jQuery selector function used for selecting the elements?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


1 Answers

The parents function does what you want:

$(this).parents("tr:first"); 
like image 134
Seb Avatar answered Sep 17 '22 18:09

Seb