To override an important style in the style sheet you need to set the style attribute with js:
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].setAttribute('style', 'background-color: red !important');
}
p.example {
background-color: blue !important;
}
<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>
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>
Try this:
function myFunction() {
var x = document.querySelectorAll("#testDiv p.example");
x[0].style.setProperty("background-color", "red", "important");
}