How to get only direct child elements by jQuery function

JqueryParent Child

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

You can use find():

tbl.find("> tbody > tr")

Solution 2 - Jquery

As @jave.web mentioned in the comments

To search through the direct children of an element use .children(). It will only search through the direct children and not traverse any deeper. http://api.jquery.com/children/

Solution 3 - Jquery

This is exactly the reason why one should be careful with nesting tables. I really hope that you use them for data and not page layout.

Another issue that will probably ruin your day is using CSS selectors on nested tables... you basically have the same issue - you are unable to select TR elements of the outer table without selecting those inside the inner table, too. (You cannot use the child selector because it is not implemented in IE6)

This should work:

$("#table1 > tbody > tr")

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

Solution 4 - Jquery

Solution 5 - Jquery

If you have ids of both elements and you want to find direct element use below code

$("#parent > #two")

If you want a nested search you can use find. It is explained in detail here. https://handyopinion.com/jquery-selector-find-nested-child-elements/

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJason LiView Question on Stackoverflow
Solution 1 - JqueryJosh LeitzelView Answer on Stackoverflow
Solution 2 - JqueryChrisView Answer on Stackoverflow
Solution 3 - JqueryŠime VidasView Answer on Stackoverflow
Solution 4 - JqueryJeremyView Answer on Stackoverflow
Solution 5 - JqueryAhmed BilalView Answer on Stackoverflow