Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one set a CSS property with the !important flag via the DOM?

So, in my stylesheet, I have a property in a rule that matches myElement which uses the !important flag.

Then, in a script, I need to adjust that property of myElement. The code I'm using does nothing:

var myElement = document.getElementById('myElement');
myElement.style.property = 'newValue';

This threw me for a loop, because while nothing was visibly happening on my page, the element even showed with the new property value under element.style in Chrome's element inspector. So it took me a while to figure it out, but then it hit me that I have to also put the !important flag in the newValue setting. Does anyone know how to do this programmatically?

like image 825
wwaawaw Avatar asked Dec 07 '12 14:12

wwaawaw


People also ask

How do you mark a property important in CSS?

The !important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!

Can the DOM change CSS?

Every HTML element in the Javascript DOM contains a Javascript object property called style . The style object contains many properties that correspond to CSS properties, so you can set properties on the style object to change element CSS styles directly.

Which method of DOM can be used to set style?

css() method: The css() method is used to change the style property of the selected element.


1 Answers

Here you go:

myElement.style.setProperty( 'property', 'newValue', 'important' );

Live demo: http://jsfiddle.net/mJHEf/

like image 178
Šime Vidas Avatar answered Oct 20 '22 17:10

Šime Vidas