JavaScript
x
19
19
1
<div id="testDiv">
2
<h2 class="example">A heading with class="example"</h2>
3
<p class="example">A paragraph with class="example".</p>
4
</div>
5
6
<button onclick="myFunction()">Try it</button>
7
8
<style>
9
.example {
10
background-color: green !important;
11
}
12
</style>
13
14
<script>
15
function myFunction() {
16
var x = document.querySelectorAll("#testDiv p.example");
17
x[0].style.backgroundColor = "red";
18
}
19
</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
Advertisement
Answer
Try this code using CSSStyleDeclaration.setProperty():
JavaScript
1
5
1
function myFunction() {
2
var x = document.querySelectorAll("#testDiv p.example");
3
x[0].style.setProperty("background-color", "red", "important");
4
}
5