Detecting CSS Properties
One way to detect a CSS property is by directly testing it on an element and checking if it returns undefined
, as shown below:
element.style.<propertyName> != undefined
.
Simplest Approach (with some limitations)
The method mentioned above checks for the property directly and should work for most common properties, but not for all like flex-wrap.
function isStyleSupported(el, property) {
return el.style[property] != undefined;
}
var testEl = document.getElementById('test');
testEl.innerHTML = (isStyleSupported(testEl, 'flexWrap')) ? "Flex Wrap is supported" : "Flex Wrap is NOT supported";
<div id="test"></div>
To enhance support and cover more properties, you can also check with DOM prefixes.
Enhanced Method for Better Support (including flex-wrap)
var domPrefixes = 'Webkit Moz O ms Khtml'.split(' ');
function toCamelCase(cssProp) {
return cssProp.replace(/-([a-z])/gi, function(s, prop) {
return prop.toUpperCase();
});
}
function isStyleSupported(el, property) {
if (el.style[toCamelCase(property)] != undefined) {
return true; //supported
}
property = toCamelCase("-" + property);
for (var i = 0; i < domPrefixes.length; i++) {
if (el.style[domPrefixes[i] + property] !== undefined) {
return true; //supported with dom prefix
}
}
}
var divEl = document.getElementById('result'), textEl = document.getElementById('textbox');
document.getElementById('checkSupport').onclick = function() {
divEl.innerHTML = (isStyleSupported(divEl, textEl.value)) ? textEl.value + " is supported" : textEl.value + " is NOT supported";
};
<input type="text" id="textbox" value="flex-wrap" />
<button id="checkSupport">Check</button>
<div id="result"></div>
If you need to generalize this for various properties across different browsers, consider using modernizr
for better coverage.
There is a new CSS API called CSS.supports
which provides a boolean value to check if a specific CSS feature is supported by the browser. While this is a great option, older browsers may still require plugins like modernizr
.
Conclusion:
For basic style detection, use
element.style.<property> != undefined
or consider including
domPrefixes
. If your needs are more complex, opt for
modernizr
for comprehensive feature detection.