Reputation: 2302
So I've already got the text color of a select box set with an !important
value and am struggling to change it again using jQuery.
<div class="halio-form-container">
...
<select class="form-control" id="HalioDirection" name="halio_direction">
<option selected="" disabled="">Direction...</option>
<option value="one_way">One Way</option>
<option value="return">Return</option>
</select>
...
</div>
.halio-form-container select {
color: #B0A9A9 !important;
}
Any thoughts?
Upvotes: 2
Views: 1317
Reputation: 35491
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:
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>
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>
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:
Upvotes: 1