Victor Victor - 4 months ago 20
CSS Question

Can I check if a CSS property is valid with jQuery?

I'm building a simple CSS editor and I want to let the user to edit CSS properties of an element or to add a new one.

Before applying the new CSS property to the element, I want to check if the property is valid.

Do you know a simple way to check if a CSS property/value is valid with jQuery?

UPDATE:

Example:

$('#some-element').css('margin','10px'); //this is valid and it will be applied
$('#some-element').css('margin','asds'); //this is not valid and it will not be applied


How to check, before applying the property, that
margin: asds;
is not valid?

Answer

You can create a new element and apply your CSS to it. You read the initial value, apply your css to this element and immediately read the value again. If the new value does not equal the initial value, your css is valid (because it has been successfully applied to the element).

var div = $("<div>");
var _old = div.css(property);
div.css(property,value);
var _new = div.css(property);
console.log( property+":"+value+"; is valid:"+(_old!=_new) );

Example fiddle