The best solution is to not use the !important
at all and refactor your css (and possibly markup) such that proper selector specificity allows you to do what you need without !important
.
That being said, general way to override an !important
is to add another CSS rule with !important
with either a higher specificity, or same specificity but defined at a later point. This works because in a specificity tie, the last rule defined wins.
Related question: How to override !important
Since we need to use JS/jQuery and not CSS, there are three possible solutions:
1. Add an inline !important rule
We can beat !important
with a more-specific rule by adding an inline !important
rule.
The reason this works is because inline styles always overwrite any styles in external stylesheets, and thus can be thought of as having the highest specificity.
var currentStyle = $('#test').attr('style') || '';
$('#test').attr('style', currentStyle + ' color:red !important');
#test {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
This text is RED, not BLUE
</div>
2. Add a new style element
We can beat !important
with a later-defined-equally-specific !important
rule by creating another stylesheet containing this rule and appending it to <head>
.
$('<style>#test { color:red !important; }</style>').appendTo('head');
#test {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
This text is RED, not BLUE
</div>
3. Append to last style element
Basically another version of 2.
where, instead of creating a new style, we append our new rule to the end of the last style:
var lastStyle = $('style').last();
lastStyle.html(lastStyle.html() + '\n#test { color:red !important; }');
#test {
color: blue !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="test">
This text is RED, not BLUE
</div>
Additional resources:
MDN