How Can I Apply '!important' Styles Using jQuery's `.css()` Method?
Dec 15, 2024 pm 06:59 PMApplying !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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Replace String Characters in JavaScript

Custom Google Search API Setup Tutorial

8 Stunning jQuery Page Layout Plugins

Improve Your jQuery Knowledge with the Source Viewer

10 Mobile Cheat Sheets for Mobile Development
