Is there a better way to select tables based on how many rows they have via jQuery?
I'm looking to grab a group of tables that have more than X rows with jQuery. Currently, I'm doin开发者_JAVA百科g 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
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.
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.
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.
精彩评论