Skip to content
Advertisement

Using CSS !important with JavaScript

<div id="testDiv">
  <h2 class="example">A heading with class="example"</h2>
  <p class="example">A paragraph with class="example".</p>
</div>

<button onclick="myFunction()">Try it</button>

<style>
  .example {
    background-color: green !important;
  }
</style>

<script>
  function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.backgroundColor = "red";
  }
</script>

From the code above, how can I override css property by !important in the above style property from my JS code defined in script tag ?

Note: We have some internal applications that have their styles declared important

Answer

Try this code using CSSStyleDeclaration.setProperty():

function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.setProperty("background-color", "red", "important");
}
Advertisement