views:

555

answers:

5

NOTE: QUESTION HAS BEEN EDITED FROM ORIGINAL FOR CLARITY

Hi all,

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. Thanks very much.

+3  A: 

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.

Matti Virkkunen
@Matti, thanks for the quick response. Can you post an example of this?
Mega Matt
The :has(tr) was the example. To elaborate, to check whether a certain jQuery object matches it, you can do myObject.is(":has(tr)"). To select any tables containing rows you'd do $("table:has(tr)"), and so on.
Matti Virkkunen
So it sounds like I'm going to use $("table").is(":has(tr)")? I need a boolean expression that returns true if a table has <tr> elements, and false otherwise... Thanks for your responses
Mega Matt
@Mega Matt: just try it. what's the problem?
just somebody
+1  A: 

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

marcgg
@marcgg, I'm really just trying to check to see if a parent element has a certain tag under it. I think the :has selector is the right path. Are you able to post example code using this method?
Mega Matt
+1  A: 

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

Mark
Actually, this isn't quite right, in hindsight. Size is a function, and should have open/close parens after it. So:`if (jQuery('table').find('tr').size() > 0) {`
Mega Matt
Oh yeah, my mistake. Thats a typo and would have been caught in the JS error console. Updated with the fix.
Mark
+1  A: 
if ($('#myTable tr').length) {
//got some tr
}
yedpodtrzitko
+1  A: 

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.

Ryan