Home > Web Front-end > JS Tutorial > How Can I Apply '!important' Styles Using jQuery's `.css()` Method?

How Can I Apply '!important' Styles Using jQuery's `.css()` Method?

Barbara Streisand
Release: 2024-12-15 18:59:11
Original
706 people have browsed it

How Can I Apply

Applying !important Style with .css()

When attempting to apply a style with the "!important" attribute using jQuery's ".css()" method, you may encounter issues. While the following code:

$("#elem").css("width", "100px !important");
Copy after login

seems intuitive, it doesn't apply the width style due to jQuery's inability to parse "!important." To overcome this, consider the following alternatives:

Using addClass()

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

.importantRule { width: 100px !important; }
Copy after login

Then, add this class to the target element:

$('#elem').addClass('importantRule');
Copy after login

Using attr()

Set the "style" attribute of the element with the "!important" style:

$('#elem').attr('style', 'width: 100px !important');
Copy after login

Note that this overwrites any existing inline styles.

Preserve Existing Inline Styles

To preserve existing inline styles while adding the "!important" style:

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

This approach appends the "!important" style to the original inline style string.

The above is the detailed content of How Can I Apply '!important' Styles Using jQuery's `.css()` Method?. 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