Freigeben über


Feature Detection Script for CSS3 Selectors

If you are a serious HTML5|CSS3 developer, you have undoubtedly come across the amazing resource known as Modernizr.  Modernizr is an amazing suite of script functions that enable feature detection to provide intelligent rendering across the multiple browsers that do or don’t support the desired feature.

Recently I was in need of a specific feature detection in CSS3 that I realized was not in the latest version of Modernizr – the ability to detect support for CSS3 Selectors.  Some examples of new CSS3 selectors include:  ::selection, :root, :target, :not, :checked, :empty … just to name a few. With necessity being the mother of invention, I took it upon myself to create the script needed to do the job. 

Here is the script, and I look forward to any feedback Smile

 // elsewhere in script use this way:  
// var result = Palermozr.isSelectorSupported(":root");
var Palermozr = (function () {
    function isSelectorSupported(anySelector) {
        var newStyle = document.createElement("style"),
                cssRule = anySelector + "{}",
                isSupported = false,
                styles,
                rules,
                selectorText;
        newStyle.type = "text\/css";
        if (newStyle.styleSheet) {
            styles = newStyle.styleSheet;
            if (styles.cssText) {
                styles.cssText = cssRule;
                if (styles.rules) {
                    rules = styles.rules;
                    if (rules[0].selectorText) {
                        selectorText = rules[0].selectorText.toLowerCase();
                        isSupported = selectorText.indexOf("unknown") < 0;
                    }
                }
            }
        } else {
            newStyle.appendChild(document.createTextNode(cssRule));
            document.body.appendChild(newStyle);
            isSupported = !!newStyle.sheet.cssRules.length;
            document.body.removeChild(newStyle);
        }
        return isSupported;
    }
    return {
        isSelectorSupported: isSelectorSupported
    };
})();