Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get only direct child elements by 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 variable tbl with value of $(table1), and then I want to get all direct child elements (tr) of <tbody> of table1. My code is :

$('tr', tb1) 

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

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

or this kind of logic.

I know $('table1 > tbody > tr') can get the direct child tr. Unfortunately I can not use this.

Anyone has good idea about this?

Thanks.

like image 793
Jason Li Avatar asked Sep 10 '10 19:09

Jason Li


People also ask

Which will select all direct child elements in jQuery?

The ("parent > child") selector selects all elements that are a direct child of the specified element.

How do you get children of children in jQuery?

Definition and Usage. The children() method returns all direct children of the selected element. The DOM tree: This method only traverse a single level down the DOM tree. To traverse down multiple levels (to return grandchildren or other descendants), use the find() method.

Can we get the children element from the parent element using jQuery?

jQuery children() method is used to get the direct children of the selected HTML element. You can use children() method to traverse through the child elements of the selected parent element.

How do you get the children of the $( this selector?

Answer: Use the jQuery find() Method You can use the find() method to get the children of the $(this) selector using jQuery. The jQuery code in the following example will simply select the child <img> element and apply some CSS style on it on click of the parent <div> element.


1 Answers

You can use find():

tbl.find("> tbody > tr")

like image 104
Josh Leitzel Avatar answered Sep 26 '22 05:09

Josh Leitzel