The "real reason", I can not say, we would have to ask John Resig, the creator of jQuery. It may have to do with compatibility between browsers, performance, or with the library's own history (it was implemented in such a way that it would be costly to change now). If I were to kick, I would kick in as the main reason compatibility - guess what browser?
What I can explain is how this really works in jQuery. But before:
How to set a style !important
with pure JavaScript?
In the browser I'm in now (Chrome), only three ways work:
el.setAttribute('style', 'color: green !important');
// ou
el.style.cssText = 'color: green !important';
// ou
el.style.setProperty('color', 'green', 'important');
// NÃO FUNCIONAM:
// el.style.color = 'green !important';
// el.style['color'] = 'green !important';
// el.style = 'color: green !important';
The first option overrides the attribute style
of the element, as if you had set style="..."
to the HTML itself. This also instructs the browser to reprocess the style of that element.
The second and third options work by modifying a property or by calling a method of the style object, which is an object of type CSSStyleDeclaration
. This interface was defined in the CSS 2.1 specification (today it is part of the CSSOM drafts ). Incidentally, IE only supports this from version 9 , which makes me suspect compatibility as a big reason jQuery does not support !important
.
The second option, el.style.cssText
, is equivalent to the first, and overwrites all style
of the element. The third option, el.style.setProperty
, is more selective, and operates over a specific property of the style
object, whose name must be passed as the first argument. It is the "correct" way (from the point of view of the specification) of setting !important
, since it has a third parameter priority exactly for this.
And how does .css
of jQuery really work?
When you call $('seletor').css('color', 'green')
, jQuery first loops over all elements that match the selector. In this case where .css
is invoked as setter , it calls the internal method jQuery.style
" for each element, passing the element as the first parameter, the property as the second, and the value as the third. This method makes some normalizations (like adding px
to the value if it is numeric), and in the end does something equivalent to this:
el.style[prop] = value;
Note that this is one of the formats that do not work to set !important
. And that's why it's no use passing !important
to the value used with .css
. This also explains why Sergio's suggestion works: .css("cssText", "color: green !important;")
is equivalent to el.style['cssText'] = 'color: green !important;'
, which is the variation of the second pure JS version I mentioned (but accessing the property with square brackets instead of dot).