I am having trouble applying a style that is !important
. I’ve tried:
$(\"#elem\").css(\"width\", \"100px
There's no need to go to the complexity of @AramKocharyan's answer, nor the need to insert any style tags dynamically.
Just overwrite style, but you don't have to parse anything, why would you?
// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
// Remove previously defined property
if (element.style.setProperty)
element.style.setProperty(property, '');
else
element.style.setAttribute(property, '');
// Insert the new style with all the old rules
element.setAttribute('style', element.style.cssText +
property + ':' + value + ((important) ? ' !important' : '') + ';');
}
Can't use removeProperty()
, because it won't remove !important
rules in Chrome.
Can't use element.style[property] = ''
, because it only accepts camelCase in Firefox.
You could probably make this shorter with jQuery, but this vanilla function will run on modern browsers, Internet Explorer 8, etc.