How can you determine if a css class exists with Javascript?

前端 未结 10 1034
闹比i
闹比i 2020-11-27 04:14

Is there a way to determine whether or not a css class exists using JavaScript?

10条回答
  •  时光说笑
    2020-11-27 04:33

    Here is my solution to this. I'm essentially just looping through document.styleSheets[].rules[].selectorText as @helen suggested.

    /**
     * This function searches for the existence of a specified CSS selector in a given stylesheet.
     *
     * @param (string) styleSheetName - This is the name of the stylesheet you'd like to search
     * @param (string) selector - This is the name of the selector you'd like to find
     * @return (bool) - Returns true if the selector is found, false if it's not found
     * @example - console.log(selectorInStyleSheet ('myStyleSheet.css', '.myClass'));
     */    
    
    function selectorInStyleSheet(styleSheetName, selector) {
        /*
         * Get the index of 'styleSheetName' from the document.styleSheets object
         */
        for (var i = 0; i < document.styleSheets.length; i++) {
            var thisStyleSheet = document.styleSheets[i].href ? document.styleSheets[i].href.replace(/^.*[\\\/]/, '') : '';
            if (thisStyleSheet == styleSheetName) { var idx = i; break; }
        }
        if (!idx) return false; // We can't find the specified stylesheet
    
        /*
         * Check the stylesheet for the specified selector
         */
        var styleSheet = document.styleSheets[idx];
        var cssRules = styleSheet.rules ? styleSheet.rules : styleSheet.cssRules;
        for (var i = 0; i < cssRules.length; ++i) {
            if(cssRules[i].selectorText == selector) return true;
        }
        return false;
    }
    

    This function offers a speed improvement over other solutions in that we are only searching the stylesheet passed to the function. The other solutions loop through all the stylesheets which is in many cases unnecessary.

提交回复
热议问题