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

前端 未结 10 1037
闹比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:46

    /* You can loop through every stylesheet currently loaded and return an array of all the defined rules for any selector text you specify, from tag names to class names or identifiers.

    Don't include the '#' or '.' prefix for an id or class name.

    Safari used to skip disabled stylesheets, and there may be other gotchas out there, but reading the rules generally works better across browsers than writing new ones. */

    function getDefinedCss(s){
        if(!document.styleSheets) return '';
        if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE capitalizes html selectors 
    
        var A, S, DS= document.styleSheets, n= DS.length, SA= [];
        while(n){
            S= DS[--n];
            A= (S.rules)? S.rules: S.cssRules;
            for(var i= 0, L= A.length; i

    getDefinedCss('p')//substitute a classname or id if you like

    the latest item in the cascade is listed first.

提交回复
热议问题