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
Release: 2024-12-11 13:14:11
Original
221 people have browsed it

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; }
      Copy after login
    • Apply the class to the target element:

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

    • This method overwrites any existing inline styles:

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

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

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template