Home > Web Front-end > JS Tutorial > body text

How to Override !important Style Rules in JavaScript?

Susan Sarandon
Release: 2024-10-28 11:53:27
Original
679 people have browsed it

How to Override !important Style Rules in JavaScript?

Overriding !important Style Rules in JavaScript

When trying to modify the appearance of an HTML element, you may encounter !important CSS declarations that seem to prevent overrides from JavaScript. This can be frustrating, but it is possible to bypass these !important rules.

Using Inline Attribute

One method is to assign a 'style' attribute directly to the element. This style attribute should include the desired property and value. By appending !important to the value, you can override the external !important declaration.

element.setAttribute('style', 'display:inline !important');
Copy after login

Modifying CSS Text Property

Alternatively, you can modify the element's style object's 'cssText' property. This property contains the entire CSS code of the element. By assigning a new CSS code to this property, you can override the existing styles, including any !important rules.

element.style.cssText = 'display:inline !important';
Copy after login

Using jQuery Plugin

For a convenient solution, you can use my jQuery plugin called "important" available on GitHub. This plugin provides additional functions for manipulating !important rules in elements.

setProperty Method

Additionally, CSSOM (CSS Object Model) offers a method called 'setProperty' that allows you to set CSS properties with a specific priority. You can use this method to override !important rules.

element.style.setProperty('background-color', 'red', 'important');
Copy after login

By employing any of these methods, you can successfully override !important style rules using JavaScript.

The above is the detailed content of How to Override !important Style Rules in 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!