What is an efficient way to set a CSS class for every cell in a given row of a table?

I have a problem setting the CSS class for each cell in a given row of a table. I originally thought that setting the parent CSS string would affect the style properties of the cells, but that doesn't work. Instead, I need to loop through all the cells in a given row in order to update the CSS class.

However, this is ineffective. And it took a long time. Consider my situation: I have about 230 rows in which each row contains 23 cells (5290 cells in total).

Note: I am not using any frameworks. so can you please suggest a native JS approach?

UPDATE:

his working fine, using Paolo's recommendation.

Originally my custom CSS class was like

.Grid_RowItalicsBold { PADDING-RIGHT: 5px; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; OVERFLOW: hidden; COLOR: Black; LINE-HEIGHT: 15pt; FONT-STYLE: normal; FONT-FAMILY: Verdana, Arial, Sans-Serif; WHITE-SPACE: nowrap; BACKGROUND-COLOR: yellow; TEXT-DECORATION: none }

      

And I changed it to

tr.Grid_RowItalicsBold td{ PADDING-RIGHT: 5px; PADDING-LEFT: 8px; FONT-WEIGHT: bold; FONT-SIZE: 8pt; OVERFLOW: hidden; COLOR: Black; LINE-HEIGHT: 15pt; FONT-STYLE: normal; FONT-FAMILY: Verdana, Arial, Sans-Serif; WHITE-SPACE: nowrap; BACKGROUND-COLOR: yellow; TEXT-DECORATION: none }

      

And I assigned this class to my specific strings using javascript. :)

+2


source to share


3 answers


Why can't you set the string class and adjust your CSS accordingly?

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

      

Then in CSS:

tr.myclass td {
    ...
}

      



In any case, if the table has the id "mytable", you can give all the rows of the table the class you want, for example:

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

      

If you are doing this with an entire table, you can simply give the class to the table tag itself, then do:

table.myclass tr td {
    ...
}

      

+15


source


@kris, the classes used in cells are common to whole cells. I only need to update selected rows .. so I can't just update this ...

It still seems like you should be using a CSS selector 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>

      

+2


source


I originally thought that setting the parent CSS string would affect the styling of the cells property, but that doesn't work.

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

0


source







All Articles