How to apply !important using .css()?

后端 未结 30 3029
情深已故
情深已故 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:26

    Instead of using the css() function try the addClass() function:

      <script>
      $(document).ready(function() {
        $("#example").addClass("exampleClass");
      });
      </script>
    
      <style>
      .exampleClass{
        width:100% !important;
        height:100% !important;
      }
      </style>
    
    0 讨论(0)
  • 2020-11-21 07:26

    Do it like this:

    $("#elem").get(0).style.width= "100px!important";
    
    0 讨论(0)
  • 2020-11-21 07:28

    You can do this:

    $("#elem").css("cssText", "width: 100px !important;");
    

    Using "cssText" as the property name and whatever you want added to the CSS as its value.

    0 讨论(0)
  • 2020-11-21 07:30

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

    $("#elem").width(100);
    

    Updated for comments: You 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');
    
    0 讨论(0)
  • 2020-11-21 07:30

    If it is not so relevant and since you're dealing with one element which is #elem, you can change its id to something else and style it as you wish...

    $('#elem').attr('id', 'cheaterId');
    

    And in your CSS:

    #cheaterId { width: 100px;}
    
    0 讨论(0)
  • 2020-11-21 07:30

    FYI, it doesn't work because jQuery doesn't support it. There was a ticket filed on 2012 (#11173 $(elem).css("property", "value !important") fails) that was eventually closed as WONTFIX.

    0 讨论(0)
提交回复
热议问题