Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - select parent by child class?

Tags:

jquery

dom

How can I select the <tr> containing the child <div class="test">, as below?

<table>   <tr> <!-- this tr is what I want to select -->     <td>       <div class="test"> text </div>     </td>   </tr> </table> 
like image 792
Moamen Avatar asked Mar 04 '12 17:03

Moamen


People also ask

What is a parent child selector?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

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.

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.

What does $( Div parent will select?

The :parent Selector page on jQuery says: Select all elements that have at least one child node (either an element or text). So $('div') would select all divs and $('div:parent') would select only those with children.


2 Answers

You can use parents or closest for that, depending on your needs:

$("div.test").parents("tr"); // Or $("div.test").closest("tr"); 

(The initial selector can be anything that matches your div, so ".test" would be fine too.)

parents will look all the way up the tree, possibly matching multiple tr elements if you have a table within a table. closest will stop with the first tr it encounters for each of the divs.

Here's an example using closest:

Live copy | Live source

HTML:

<table>   <tr id="first"> <!-- this tr I want to select -->     <td>       <div class="test"> text </div>     </td>   </tr>   <tr id="second"> <!-- this tr I want to select -->     <td>       <div class="test"> text </div>     </td>   </tr>   <tr id="third"> <!-- this tr I want to select -->     <td>       <div class="test"> text </div>     </td>   </tr> </table> 

JavaScript:

jQuery(function($) {    var rows = $("div.test").closest("tr");   display("Matched " + rows.length + " rows:");   rows.each(function() {     display("Row '" + this.id + "'");   });    function display(msg) {     $("<p>").html(msg).appendTo(document.body);   } }); 

Output:

Matched 3 rows: Row 'first' Row 'second' Row 'third'
like image 162
T.J. Crowder Avatar answered Oct 19 '22 03:10

T.J. Crowder


Use selector :has() like:

$("tr:has(div.test)"); 

Find jQuery documentation here :has() Selector

like image 29
Iakovos Exadaktylos Avatar answered Oct 19 '22 01:10

Iakovos Exadaktylos