views:

55

answers:

3

I'm looking to grab a group of tables that have more than X rows with jQuery. Currently, I'm doing something similar to:

    $("table").each(function(){
 if($(this).find("tr").length > x){
  tableArray[tableArray.length] = $(this);
 }
});

and then acting on the members of the tableArray.

Is there a better way of getting these tables, perhaps a nice selector I've missed?

Thanks

A: 

Check this one
http://api.jquery.com/nth-child-selector/

$("table tr:nth-child(" + (x + 1) + ")").parent();

Didn't test it, but should be close. Note, you may need two ".parent()" calls, depending on your table structure.

Nikita Rybak
+3  A: 

Try using the :has selector:

$('table:has(tr:eq('+x+'))');

That would only grab tables that have a row x. Note that :eq() takes a zero-based index as its parameter, meaning if x is 1, tables containing 2 rows or more would be selected.

EDIT :has is falling over for me, with :nth-child and :eq. .has() (the method equivalent of the selector) works though:

alert($('table').has("tr:nth-child(2)").length)​

Although, note that the parameter passed to nth-child is not zero-based like :eq is.

Example - alerts the number of tables found with 2 rows or more.

Andy E
Strange, but :has doesn't seem to like :eq, 0 is always returned. http://jsfiddle.net/S2EE2/ (never used :has before, so decided to try now)
Nikita Rybak
@Nikita Rybak: way ahead of you :-) See my edits and my example http://jsfiddle.net/baNAJ/.
Andy E
Thanks for the reply. I'm using this problem in a Firefox extension, and it seems to contradict what your example shows. Since the .has() selector just goes one descendant down, I think the <tbody> is confusing it. It's a shame the :nth-child doesn't work properly with :has, which can go to any child depth. I guess I'll use my current solution.
bubbahotep
@bubbahotep: `.has()` goes through all descendants - *Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element*. Also, if you check my linked example, those tables have `<tbody>` elements. Maybe the problem lies elsewhere?
Andy E
A: 

I think your way is fine, frankly.

One alternate way would be to use the :has selector in conjunction with nth-child: ask jQuery for $("tbody:has(:nth-child(4))).... This says "find all tables whose tbody elements have 4 or more children". Since the children of a tbody are typically tr elements, this will do the trick.

John Feminella