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
Barbara StreisandOriginal
2024-12-15 18:59:11758browse

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");

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; }

Then, add this class to the target element:

$('#elem').addClass('importantRule');

Using attr()

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

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

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;' });

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!

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