Skip to content Skip to sidebar Skip to footer

What Is An Efficient Way To Set CSS Class For Each Cell In A Given Table Row?

I have a problem setting the CSS class for each cell in a given table row. Initially I thought setting the parent row CSS would affect the style properties of cells, but that does

Solution 1:

Why can't you set the class of the row and adjust your css accordingly?

<tr class="myclass">
   <td>...</td>
   <td>...</td>
</tr>

Then in CSS:

tr.myclass td {
    ...
}

In either case, assuming the table has an id of "mytable" you could give all the table rows the class you want like so:

var rows = document.getElementById('mytable').getElementsByTagName('tr');
for(var x = 0; x < rows.length; x++) {
    rows[x].className = rows[x].className + " myclass";
}

If you're doing this to the whole table, though, you might as well just give a class to the table tag itself then do:

table.myclass tr td {
    ...
}

Solution 2:

@kris, the classes used in cells are common for entire cells.. i need to update only the selective rows.. so i cant just update that...

It still seems like you should be using CSS selectors to do what you want. Maybe something like this:

  #mytable td {
    // regular td style
  }
  #mytable .special td {
    // special cell style
  }

<table id="mytable">
  <tbody>
    <tr>
      <td>Data</td>
      <td>Data</td>
    </tr>
    <tr class="special">
      <td>Data</td>
      <td>Data</td>
    </tr>
  </tbody>
</table>

Solution 3:

Initially I thought setting the parent row CSS would affect the style properties of cells, but that doesn't work.

I think that if you set some of your cell's properties to "inherit" they will inherit those properties from the table row. Have you tried that?


Post a Comment for "What Is An Efficient Way To Set CSS Class For Each Cell In A Given Table Row?"