javascript tutorial - [Solved-5 Solutions] How to apply !important using .css ? - javascript - java script - javascript array



Problem:

We am having trouble applying a style that is !important. I’ve tried:

$("#elem").css("width", "100px !important");
click below button to copy the code. By JavaScript tutorial team

This does nothing; no width style whatsoever is applied. Is there a jQuery-ish way of applying such a style without having to overwrite cssText (which would mean I’d need to parse it first, etc.)?

Solution 1:

We think I've found a real solution. I've made it into a new function:

jQuery.style(name, value, priority); We can use it to get values with .style('name') just like .css('name'), get the CSSStyleDeclaration with .style(), and also set values - with the ability to specify the priority as 'important'. See

Demo

var div = $('someDiv');
console.log(div.style('color'));
div.style('color', 'red');
console.log(div.style('color'));
div.style('color', 'blue', 'important');
console.log(div.style('color'));
console.log(div.style().getPropertyPriority('color'));
click below button to copy the code. By JavaScript tutorial team

Here's the output:

null
red
blue
important
click below button to copy the code. By JavaScript tutorial team

The Function

(function($) {    
  if ($.fn.style) {
    return;
  }

  // Escape regex chars with \
  var escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  };

  // For those who need them (< IE 9), add support for CSS functions
  var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
  if (!isStyleFuncSupported) {
    CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
      return this.getAttribute(a);
    };
    CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
      this.setAttribute(styleName, value);
      var priority = typeof priority != 'undefined' ? priority : '';
      if (priority != '') {
        // Add priority manually
        var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
            '(\\s*;)?', 'gmi');
        this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
      }
    };
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
      return this.removeAttribute(a);
    };
    CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
      var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
          'gmi');
      return rule.test(this.cssText) ? 'important' : '';
    }
  }

  // The style function
  $.fn.style = function(styleName, value, priority) {
    // DOM node
    var node = this.get(0);
    // Ensure we have a DOM node
    if (typeof node == 'undefined') {
      return this;
    }
    // CSSStyleDeclaration
    var style = this.get(0).style;
    // Getter/Setter
    if (typeof styleName != 'undefined') {
      if (typeof value != 'undefined') {
        // Set style property
        priority = typeof priority != 'undefined' ? priority : '';
        style.setProperty(styleName, value, priority);
        return this;
      } else {
        // Get style property
        return style.getPropertyValue(styleName);
      }
    } else {
      // Get CSSStyleDeclaration
      return style;
    }
  };
})(jQuery);
click below button to copy the code. By JavaScript tutorial team
  • See this CSSStyleDeclaration for examples of how to read and set the CSS values. My issue was that we had already set !important for the width in my CSS to avoid conflicts with other theme CSS, but any changes WE made to the width in jQuery would be unaffected since they would be added to the style attribute.
  • Compatibility
  • For setting with the priority using the setProperty function, This Article ljdpsdnb says there is support for IE 9+ and all other browsers. WE have tried with IE 8 and it has failed, which is why WE built support for it in my functions (see above). It will work on all other browsers using setProperty, but it will need my custom code to work in < IE 9.

Solution 2:

The problem is caused by jQuery not understanding the !important attribute, and as such fails to apply the rule. We might be able to work around that problem, and apply the rule by referring to it, via addClass():

.importantRule { width: 100px !important; }

$('#elem').addClass('importantRule');
click below button to copy the code. By JavaScript tutorial team

Or by using attr():

$('#elem').attr('style', 'width: 100px !important');
click below button to copy the code. By JavaScript tutorial team
  • The latter approach would unset any previously set in-line style rules, though. So use with care.
  • Of course, there's a good argument that @Nick Craver's method is easier/wiser.
  • The above, attr() approach modified slightly to preserve the original style string/properties:
$('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' })
click below button to copy the code. By JavaScript tutorial team

Solution 3:

We can set the width directly using .width() like this:

$("#elem").width(100);
click below button to copy the code. By JavaScript tutorial team

Updated for comments: We have this option as well, but it'll replace all css on the element, so not sure it's any more viable:

$('#elem').css('cssText', 'width: 100px !important');
click below button to copy the code. By JavaScript tutorial team

Solution 4:

	var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');

click below button to copy the code. By JavaScript tutorial team

Solution 5:

After reading other answers and experimenting, this is what works for me:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
click below button to copy the code. By JavaScript tutorial team

This doesn't work in IE 8 and under, though.


Related Searches to javascript tutorial - How to apply !important using .css ?