tags:

views:

87

answers:

3
$(this).parents('table:first').find('tr'))

The above will search for tr inside table recursively,how to make it only search for the top tr?

EDIT

children is not working as expected:

alert($(this).parents('table:first').children('tr').length)

gives 0

+4  A: 
$('table > tr')

This will find <tr> tags that are direct children of the table. If the rows are inside a tbody, you'd have to do this: $('table > tbody > tr')

Wesley Petrowski
`tbody` is usually added implicitly by browsers, so that's the correct path. (iirc, even ie6 adds tbody)
Kobi
Is there a stable solution that will work in all browsers with no doubt?
Sure. Add `<tbody>` explicitly to your markup, don't leave room for chance :)
Kobi
So no solution without re-touching markup?
yeah ff will add tbody so not a good answer as it will fail. Always add tbody to the markup $('table > tbody > tr')
redsquare
+1  A: 

$('table > tr') should work correctly. Or $('table').children('tr').

Andrey Shchekin
After replace find with children,it stops works totally.
That doesn't make any sense that it would stop working. You should post an example of your code in case you have tbody tags or something.
Soviut
@Soviut :$('table').children('tr').length is 0
I think it is probably 'tbody' problem from the above post, so it should be $('table > tbody > tr') or $('table').children('tbody').children('tr') or any combination of the two.
Andrey Shchekin
But not all browser will do it that way,right?Is there a stable solution?
Well, this _may_ work in all browsers: $this.parents('table').find('> tr, > tbody > tr')
Andrey Shchekin
+4  A: 
$(this).parents('table:first').find('> tbody > tr, > tr')

Will grab the table and then find all tr's that are direct children of tbody and those tr's that are direct children of the table.

Should work in both cases where the browser adds tbody and when the browser does not

PetersenDidIt
This is the best solution, IMO. I've edited to make a slight change to the code so it will still work with nested tables (finds just the immediate `tbody` children, not all descendants).
nickf
Why the down vote?
PetersenDidIt