Skip to content Skip to sidebar Skip to footer

Change Background Color Of Div With Jquery That Has An !important Tag

Using a plugin that calls a .jsp that uses its own stylesheet hosted externally (it's a yelp embed - trying to manipulate the look of it). The one element I'm trying to change has

Solution 1:

It looks like in more up-to-date versions of jQuery (at least 1.7.2 and higher) you can simply set the css:

$('#elementToChange').css('background-color', 'blue');

See http://jsfiddle.net/HmXXc/185/

In older versions of jQuery and Zepto you had to clear the css first:

// Clear the !important css
$('#elementToChange').css('background-color', '');

And then reset it using:

$('#elementToChange').css('background-color', 'blue');

Or in a one-liner:

$('#elementToChange')
    .css('background-color', '')
    .css('background-color', 'blue');

See http://jsfiddle.net/HmXXc/186/.

Original answer:

Note: this may be a bad idea, as it will remove any other inline styles

I would edit the style attribute directly

$('.elementToChange').attr('style', 'background-color: blue !important');

http://jsfiddle.net/RichardTowers/3wemT/1/

Solution 2:

Solution 3:

You can manipulate !important css by using following steps, either you can use inline-css or Internal css or you can load your own external css after the order of that preloaded css, it will help you to override that css with your custom one.

<html><head><!--
    //First Solution
    //PreloaderCSS
    //YourCustomCSS

    //Second Solution
    Internal CSS --></head><body><!--
Third solution
//Inline CSS
->
    </body>
    </html>

Solution 4:

You can use the following function:

functionreplaceBGColorImportant(element,newColor){
    var styles = element.getAttribute('style');
    styles = styles?styles.split(';'):[];
    var newStyles = [];
    styles.map(function(x){
        if (x.split(':')[0] != "background-color")
            newStyles.push(x);
    });
    newStyles.push('background-color:#'+newColor+' !important');
    element.setAttribute('style',newStyles.join(';'));
}

Execute as follows:

replaceBGColorImportant(document.body,'#009922');

Solution 5:

Via regular expression: https://jsfiddle.net/7jj7gq3y/2/

HTML:

<divclass="elementToChange"style=" background-color: yellow !important; width: 100px; height: 100px;"></div>

JavaScript:

var setImportantStyle = function(element, attributeName, value) {
    var style = element.attr('style');
    if (style === undefined) return;
    var re = newRegExp(attributeName + ": .* !important;", "g");
    style = style.replace(re, "");
    element.css('cssText', attributeName + ': ' + value + ' !important;' + style);
}
setImportantStyle($('.elementToChange'), 'background-color', 'red');

Post a Comment for "Change Background Color Of Div With Jquery That Has An !important Tag"