skip to Main Content

I have a table that can contain nested tables which renders inside a drawer.
The nested table is the same component, and i’m trying to create a css selector that will select the td elements of rows of the root table and not of nested tables.

I have started with the following selector:

table.querySelectorAll(`tbody tr > td:nth-child(${index + 1})`)

It indeed selected the right td elements but from all the rows of all tables. I should note that the nested table is within a div that has [data-state="open"] but it didn’t help me so far. The only way i’m thinking on how to determine a row from nested row is that it has 1 parent table element instead of 2.

Thanks

2

Answers


  1. Modifid answer:
    Select all existing TDs then filter those are not direct children of the root table:

    const rootTable = document.querySelector('table');
    const allTdElements = rootTable.querySelectorAll('td');
    
    const rootTableTdElements = Array.from(allTdElements).filter(td => {
        //Exclude TDs which are not direct children of the root table
        return td.closest('table') === rootTable;
    });
    

    Old answer which selects all TDs without filtering:

    To choose direct children you can use > which is direct child
    selector:

    table.querySelectorAll(`tbody > tr > td:nth-child(${index + 1})`);
    
    Login or Signup to reply.
  2. Use the :not selector

    td:not(tbody tbody td)
    
    td {
      padding: .5em;
      border: 1px solid grey;
      background: lightblue;
    }
    
    td:not(tbody tbody td) {
      background: lightgreen;
    }
    <table>
      <tr>
        <td></td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td>
          <table>
            <tr>
              <td></td>
              <td></td>
              <td></td>
            </tr>
            <tr>
              <td></td>
              <td></td>
              <td></td>
            </tr>
          </table>
        </td>
        <td></td>
        <td></td>
      </tr>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search