Skip to content

Instantly share code, notes, and snippets.

@levito
Forked from Skateside/supportsSelector.js
Last active December 14, 2015 04:48
Show Gist options
  • Save levito/5030380 to your computer and use it in GitHub Desktop.
Save levito/5030380 to your computer and use it in GitHub Desktop.
Detects whether or not a given CSS selector is supported by the current browser
// Detects whether or not a given CSS selector is supported by the current
// browser.
//
// Takes:
// selector (String) The CSS selector to test.
// Returns:
// (Boolean) true if the selector is supported, false
// otherwise.
var supportsSelector = (function () {
var cache = {};
return function (selector) {
var supported = false;
if (cache.hasOwnProperty(selector)) {
supported = cache[selector];
} else {
var style = document.createElement('style');
// IE needs the type to be set in order to recognise a style sheet.
// IE7 needs the style sheet to be added to the DOM before it can be
// tested.
style.setAttribute('type', 'text\/css');
document.body.appendChild(style);
if (style.styleSheet) {
// To test in IE, add the selector to the style sheet as
// cssText. If that stylsheet has any rules, the first one is a
// string and it doesn't contain "unknown" in either upper or
// lower case, the selector is supported.
style.styleSheet.cssText = selector + '{}';
var rules = style.styleSheet.rules;
supported = !!(rules && rules[0] &&
rules[0].selectorText &&
rules[0].selectorText.toLowerCase &&
rules[0].selectorText.toLowerCase().indexOf('unknown') < 0);
} else {
// Non-IE browsers allow the selector to be appended to the
// style sheet as a textNode. If the sheet still has no rules
// afterwards, the selector is not supported.
style.appendChild(document.createTextNode(selector + '{}'));
document.body.appendChild(style);
supported = !!style.sheet.cssRules.length;
document.body.removeChild(style);
}
cache[selector] = supported;
// A little tidying up never hurt anyone.
document.body.removeChild(style);
style = null;
}
return supported;
};
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment