MegaMatt
MegaMatt

Reputation: 23763

Given a Parent Element, Testing for Certain Child Elements

I have the following code:

<table id="myTable">
    <th>Date</th>
    <th>Action</th>
</table>

and

var $table = $('#myTable');

There is a condition in my JS where I will be appending table rows (<tr>) to this table, but I want to write a function to check to see if any have been added or not.

So I'm looking for a boolean expression that returns true if $table contains any <tr> tags, and false otherwise. Preliminary answers lead me to believe I need to use the jQuery ':has' selector.

Upvotes: 1

Views: 1725

Answers (5)

Mark
Mark

Reputation: 5720


if (jQuery('table').find('tr').size() > 0) {
  // has element
}

Upvotes: 2

Ryan
Ryan

Reputation: 6866

If all you're trying to do is return true if your table contains any rows and false if your table contains no rows then you can try this...

return ($("#myTable tr").length > 0);

If you're going to have a header row though that is in the table at all times you might want to change the 0 to 1 in the above script.

Upvotes: 1

yedpodtrzitko
yedpodtrzitko

Reputation: 9359

if ($('#myTable tr').length) {
//got some tr
}

Upvotes: 1

marcgg
marcgg

Reputation: 66436

You could do something like :

jQuery("table").find("certainTr").size > 1

or use the :has selector

I'm not 100% sure I understood your question... let me know if I'm off

Upvotes: 1

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

You can use the :has() selector. You can use any selector inside the parenthesis. For example, :has(tr) checks whether the element contains any tr elements.

Upvotes: 4

Related Questions