0

I have an interactive page that changes td background color dynamically, with javascript. Without any style, this page works fine. As a style requirement, table background color should be black, and td background should be white. But due to cascade rules, dynamic changes have lower priority, so javascript is not able to override static style. How can I solve this? Thanks.

Sample 1:

cell.style.cssText = "background-color: gray;" // it works fine

Sample 2:

table {
  background-color:black;
}

td {
  background-color: white;
}

cell.style.cssText = "background-color: gray;" // it does not work anymore, even with "!important;"
  • You should use css classes. Use JS to set or remove the required class. Take a look at [how-can-i-change-an-elements-class-with-javascript](https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript) – B001ᛦ Sep 18 '21 at 20:24

1 Answers1

0

Inline styles override styles defined in <style> and it works even with dynamic styling using cssText (see my code example). Your problem is probably somewhere else, e.g. in the cssText value itself (it should be background-color: gray;, not just gray

function foo() {
  document.getElementById("cell3").style.cssText = "background-color: green";
}
table {
  background-color:black;
}

td {
  background-color: red;
}
<table>
    <tr>
      <td>cell1</td>
      <td>cell2</td>
      <td id="cell3" onclick="foo()">cell3</td>
    </tr>
  </table>
user14967413
  • 1,264
  • 1
  • 6
  • 12
  • Thanks, I fixed the "background-color: gray;". I see what I was doing wrong, I wanted to change the row background, but in the sample I put cell. – Julio Otuyama Sep 18 '21 at 20:58