How to get only direct children using jQuery function

I have a table structure like this:

<table1> <tbody> <tr> <td></td> ... <td> <table2> <tbody> <tr> <td></td> </tr> </tbody> </table> </td> </tr> </tbody> </table> 

In javascript, I have a tbl variable with the value $(table1) , and then I want to get all the direct children of (tr) <tbody> of table1 . My code is:

 $('tr', tb1) 

Apparently, it returns all the <tr> elements in table1 and table2. I think I can get

 $('tr', tb1).not(function(){return $(this).parent().parent()[0] != tb1;}) 

or such logic.

I know that $('table1 > tbody > tr') can get a direct child of tr . Sorry, I cannot use this.

Anyone have a good idea about this?

Thank.

+59
jquery parent-child
Sep 10 '10 at 19:19
source share
4 answers

You can use find() :

tbl.find("> tbody > tr")

+133
Sep 10 '10 at 19:23
source share

Like @ jave.web mentioned in comments

To search for direct children of an element, use .children() . He will seek only direct children and not cross deeper. http://api.jquery.com/children/

+9
Jun 22 '15 at 21:36
source share

For this reason, you need to be careful with nesting tables. I really hope that you use them for data, not for page layout.

Another problem that is likely to ruin your day is the use of CSS selectors on nested tables ... basically you have the same problem: you cannot select TR elements of an external table without selecting them inside the internal table. (You cannot use a child selector because it is not implemented in IE6)

This should work:

 $("#table1 > tbody > tr") 

However, I recommend that you hardcode the TBODY element, as you should not rely on the browser to create one for you.

+4
Sep 10 '10 at 19:27
source share
0
Sep 10 '10 at 19:23
source share



All Articles