Home >Web Front-end >JS Tutorial >How Can I Override Inline `!important` Styles with JavaScript?

How Can I Override Inline `!important` Styles with JavaScript?

Susan Sarandon
Susan SarandonOriginal
2024-12-11 13:14:11217browse

How Can I Override Inline `!important` Styles with JavaScript?

Overriding Inline !important Styles with JavaScript

jQuery's .css() method doesn't apply styles marked with the !important attribute. This can be frustrating when trying to override existing inline styles that include !important.

Solution:

Overcome this limitation using one of these methods:

  1. Use addClass() with a Class Rule:

    • Create a CSS class with the desired !important style:

      .importantRule { width: 100px !important; }
    • Apply the class to the target element:

      $('#elem').addClass('importantRule');
  2. Use attr() to Set Inline Style:

    • This method overwrites any existing inline styles:

      $('#elem').attr('style', 'width: 100px !important');
    • To preserve existing inline styles, use this modified version:

      $('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });

The above is the detailed content of How Can I Override Inline `!important` Styles with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn