views:

62

answers:

4

I am trying to find all tr elements inside a table element. The table element it self has other table elements nested inside its rows. So when I do the following:

$(tbl).find('tr').hover(...);

...it picks up tr elements inside the nested table elements also. I just want the immediate tr elements of the table element I am trying to query.

$(tbl).find('>tr').hover(...); didn't work for me!

ps: tbl is a table element, not a string

A: 
$(tbl).children('tr').hover(...);
Codler
A: 

This should work:

$(tbl).children('tr').hover(...);

Form the JQuery docu:

The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

JochenJung
A: 

Don't forget that - even if your markup doesn't include them - from a DOM point of view, tr elements are nested inside a tbody element, so you will need to include this in the selector.

Try something like...

$(tbl).find('tbody>tr').hover(...); 

Although this will probably find the nested table's tbody too, so you'll probably need something like...

$(tbl).children().find('tr').hover(...); 
belugabob
+1  A: 

Read full answer, please.

$(tbl).children() 

will give you tbody and also thead if it exists. So if you want immediate tr, you will need to try this.

$(tbl).children('tbody').children('tr')

Don't forget to considertbody while fetching children of a table, as in Firefox a direct call to children like $(tbl).children() returns tbody and not tr, even if its not in your markup. Complex but useful.

Happy Coding.

simplyharsh
I don't know about tbody existence, but I'd so something like:`if ($(tbl).children('tbody').size() > 0) { ... } else { ... }`
deostroll