Created
November 14, 2012 10:18
-
-
Save Skateside/4071375 to your computer and use it in GitHub Desktop.
CSS selector support ion a handy function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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, | |
style = document.createElement('style'), | |
rules; | |
if (cache.hasOwnProperty(selector)) { | |
supported = cache[selector]; | |
} else { | |
// 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 + '{}'; | |
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