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>
The ("parent > child") selector selects all elements that are a direct child of the specified element.
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.
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.
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.
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 div
s.
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'
Use selector :has() like:
$("tr:has(div.test)");
Find jQuery documentation here :has() Selector
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