4

I have this code

$('#downvotebutton').click(function() {
    $(this).css('background-color', 'red !important');
    console.log('foo');
    //more

When downvotebutton is clicked, 'foo' is returned to the console but the background-color doesn't change. jQuery is linked to and works elsewhere in the page. what could possibly be the cause?

user3324865
  • 163
  • 1
  • 2
  • 10

6 Answers6

7

Do you really need !important? Following will work:

$(this).css('background-color', 'red');

Or if you need !important:

$(this).css("cssText", "background-color: red !important;");
Sergio
  • 6,900
  • 5
  • 31
  • 55
3

You cannot use !important statement using jQuery css() method.

You could use:

$(this).attr('style', function(_, rules) { 
     var newval = rules?rules:"";return newval + ';background-color: red !important;' 
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
2

You can use attr() instead since css() cannot set !important property:

$('#downvotebutton').click(function() {
    $(this).attr('style', 'background-color: red !important');
    console.log('foo');
});

Fiddle Demo

Felix
  • 37,892
  • 8
  • 43
  • 55
1

try this..

$(docuemnt).ready(function(){
$('#downvotebutton').click(function() {
    $(this).css('background-color', 'red');
    console.log('color changed');
});
});
kamesh
  • 2,374
  • 3
  • 25
  • 33
1

Use a class instead. .css doesn't support !important.

http://bugs.jquery.com/ticket/11173

mbcrute
  • 1,117
  • 1
  • 11
  • 19
1

Actually you can use !important with the .css() method.

cssText allows you to pass over a 3rd arguement, in this case !important

$('#downvotebutton').css("cssText", "background-color: red !important;");

Hope this helps!

heymega
  • 9,215
  • 8
  • 42
  • 61