How to apply !important using .css()?

后端 未结 30 2824
情深已故
情深已故 2020-11-21 07:06

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

$(\"#elem\").css(\"width\", \"100px          


        
相关标签:
30条回答
  • 2020-11-21 07:30

    We need first to remove the previous style. I remove it using a regular expression. Here is an example for changing color:

    var SetCssColorImportant = function (jDom, color) {
           var style = jDom.attr('style');
           style = style.replace(/color: .* !important;/g, '');
           jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
    
    0 讨论(0)
  • 2020-11-21 07:30

    May be it look's like this:

    Cache

    var node = $('.selector')[0];
    OR
    var node = document.querySelector('.selector');
    

    Set CSS

    node.style.setProperty('width', '100px', 'important');

    Remove CSS

    node.style.removeProperty('width');
    OR
    node.style.width = '';
    0 讨论(0)
  • 2020-11-21 07:34

    An alternative way to append style in head:

    $('head').append('<style> #elm{width:150px !important} </style>');
    

    This appends style after all your CSS files so it will have higher priority than other CSS files and will be applied.

    0 讨论(0)
  • It may or may not be appropriate for your situation but you can use CSS selectors for a lot of these type of situations.

    If, for example you wanted of the 3rd and 6th instances of .cssText to have a different width you could write:

    .cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}
    

    Or:

    .container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}
    
    0 讨论(0)
  • 2020-11-21 07:35

    We can use setProperty or cssText to add !important to a DOM element using JavaScript.

    Example 1:

    elem.style.setProperty ("color", "green", "important");
    

    Example 2:

    elem.style.cssText='color: red !important;'
    
    0 讨论(0)
  • 2020-11-21 07:36

    This solution doesn't override any of the previous styles, it just applies the one you need:

    var heightStyle = "height: 500px !important";
    if ($("foo").attr('style')) {
      $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
    else {
      $("foo").attr('style', heightStyle);
    }
    
    0 讨论(0)
提交回复
热议问题