How to select first td of first two rows using css

279 Views Asked by At

It's a complicated one I think. Let's see if I'm wrong. I want to select only the td which are marked as "// to be selected" I dont want to apply styles for any other td other than the marked ones. Please help!

<table>
  <tbody>
    <tr>
     <td> // to be selected
      <div>
       <div>
        <table>
         <tbody>
          <tr>
           <td></td>
          </tr>
         </tbody>
        </table> 
       </div>
      </div>
     </td>
   </tr>
   <tr>
     <td> // to be selected
      <div>
       <div>
        <table>
         <tbody>
          <tr>
           <td></td>
          </tr>
         </tbody>
        </table> 
       </div>
      </div>
     </td>
   </tr>
   <tr>
     <td> // to be selected
      <div>
       <div>
        <table>
         <tbody>
          <tr>
           <td></td>
          </tr>
         </tbody>
        </table> 
       </div>
      </div>
     </td>
   </tr>
  </tbody>
</table>

Thanks in Advance!

4

There are 4 best solutions below

3
On BEST ANSWER

Use td to set styles to all td elements and use td td to reset the styles to the nested td elements.

td {
  // styles
}

td td {
  // styles to reset the nested elements
}
3
On

var table = document.getElementsByTagName('table')[0]
let tbody = table.children[0];

let trs = tbody.children



for (let i = 0; i < trs.length; i++){

  var tdhtml = trs[i].getElementsByTagName('td')[0].innerHTML 
  
  trs[i].getElementsByTagName('td')[0].innerHTML ='selected' + tdhtml
  
}
<table>
  <tbody>
    <tr>
     <td> 1<!--to be selected-->
      <div>
       <div>
        <table>
         <tbody>
          <tr>
           <td></td>
          </tr>
         </tbody>
        </table> 
       </div>
      </div>
     </td>
   </tr>
   <tr>
     <td> 2<!--to be selected-->
      <div>
       <div>
        <table>
         <tbody>
          <tr>
           <td></td>
          </tr>
         </tbody>
        </table> 
       </div>
      </div>
     </td>
   </tr>
   <tr>
     <td> 3 <!-- to be selected-->
      <div>
       <div>
        <table>
         <tbody>
          <tr>
           <td></td>
          </tr>
         </tbody>
        </table> 
       </div>
      </div>
     </td>
   </tr>
  </tbody>
</table>

1
On

As suggested before (and in my opinion the best option), you can add a class to the td elements you want to select, you can also select them using specificity by using the path to those elements.

CSS    
table tbody tr td{
    /* your code here */
}
0
On

You would need to apply a CSS class to the first TD of each row in the highest level table, as follows:

/* Set all root TR's and the first TD element */
table>tbody>tr>td:first-child {
  background-color: yellow;
}

/* Reset so that this doesn't cascade */
table>tbody>tr>td:first-child td {
  background-color: inherit;
}

Example here: https://jsfiddle.net/0utqvhy6/