Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 601
Nagaraju_Y Avatar asked Jul 19 '16 09:07

Nagaraju_Y


People also ask

Is it important to use CSS?

It is the coding language that gives a website its look and layout. Along with HTML, CSS is fundamental to web design. Without it, websites would still be plain text on white backgrounds.

Which is more better to use JavaScript or CSS?

The more CSS you use, the more standarized, cross-browser, performant and maintainable web. So JavaScript as a fallback when a specific feature is not supported in CSS alone seems to be the general consensus. More flexible, easy to maintain, etc. Don't need to build a physics engine when a CSS transition will do fine.

How do I get important in JavaScript?

To set a CSS inline style as an ! important one in javascript, you have to use the element. setAttribute() method.


2 Answers

Try this code using CSSStyleDeclaration.setProperty():

function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.setProperty("background-color", "red", "important");
}
like image 126
Văn Quyết Avatar answered Oct 18 '22 19:10

Văn Quyết


Here is 2 different script, one target an element's CSS property and the other its style.

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

<p>Click the button to add a background color to the first element in the document with class="example" (index 0).</p>

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

<p><strong>Note:</strong> The querySelectorAll() method is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
  function myFunction() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style.backgroundColor = "red";
  }
  function myFunction2() {
    var x = document.querySelectorAll("#testDiv p.example");
    x[0].style = "background-color: red !important";
  }
</script>
like image 2
Asons Avatar answered Oct 18 '22 20:10

Asons