最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can one set a CSS property with the !important flag via the DOM? - Stack Overflow

programmeradmin4浏览0评论

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?

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?

Share Improve this question asked Dec 7, 2012 at 14:41 wwaawawwwaawaw 7,12710 gold badges35 silver badges42 bronze badges 2
  • 1 And so begins the !important war... Real solution is to not use it. – No Results Found Commented Dec 7, 2012 at 14:42
  • 3 this question is a great description of why using !important anywhere in your code is generally a bad idea. – SDC Commented Dec 7, 2012 at 14:43
Add a comment  | 

1 Answer 1

Reset to default 23

Here you go:

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

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

发布评论

评论列表(0)

  1. 暂无评论