<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
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.
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.
To set a CSS inline style as an ! important one in javascript, you have to use the element. setAttribute() method.
Try this code using CSSStyleDeclaration.setProperty():
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].style.setProperty("background-color", "red", "important");
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With