I'm a bit confused. I expected from $.css() method to dumbly add a css property to an element no matter what. You know, just like in Chrome Dev tools, when you apply any css property to an element and it simply appears in HTML. But apparently it somehow checks if it supported. For example, if you run this command:
$('#element').css('display','block'); /* returns jQuery object) */
$('#element').css('display') /* returns "block" */
But if you put something like
$('#element').css('hurr','durr');
$('#element').css('hurr') /* returns undefined */
So, jQuery checks if property is appliable?
Another example. Opera currently does not support CSS filters. Or does it? Well, I used a method described here and surprisingly it returned true
for 'filter'. Then I tried to apply it with $.css:
$('#element').css('filter','blur(5px)');
$('#element').css('filter') /*returns "" (an empty string) *
So, not only does jQuery check if an element is supported but even checks if value is legit. How exactly does it do that? What is the right way to check if a property is supported?
Get a CSS Property Value You can get the computed value of an element's CSS property by simply passing the property name as a parameter to the css() method. Here's the basic syntax: $(selector). css("propertyName");
You can do this: $("#elem"). css("cssText", "width: 100px ! important;");
jQuery css() Method The css() method sets or returns one or more style properties for the selected elements. When used to return properties: This method returns the specified CSS property value of the FIRST matched element.
The css function does a lot of work to standardise the different ways each browser accesses the various css properties - for example, the W3C standard property for float is cssFloat
, but Internet Explorer calls it styleFloat
.
Because of this, jQuery only works with accepted css properties. filter
is a proprietary (browser-specific) property.
jQuery is indeed filtering out some values, but it isn't doing it intentionally in this case. It has to do with how it retrieves the styles using getComputedStyle()
which apparently knows that "hurr"
isn't a valid style so it isn't returned as part of that and then when jQuery looks for "hurr
" in the computed style, it isn't there so it returns undefined
.
In Chrome, the style value does appear to actually be there on the style object, even when set via jQuery, but it isn't retrieved properly by .css()
because it's not a real style.
If you want to set an unsupported style value, you can just use the style object directly but according to some comments in the jQuery code, some versions of IE might throw an exception if you try to set something it doesn't know about:
var elem = document.getElementById("element");
elem.style.hurr = "durr";
console.log(elem.style.hurr); // in Chrome, gives you "durr"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With