tags:

views:

936

answers:

2

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

+3  A: 

This should be possible to do using the document.styleSheets[].rules[].selectorText and document.styleSheets[].imports[].rules[].selectorText properties. See this page for details and sample code.

Helen
Shadi Almosri
Thanks, I found that link earlier and tried looking at the google cache but apparently didn't scroll far enough down the page. The first few responses all had the "register to view" text on them.
gidmanma
Code is listed on the link in Shadi's comment above. Basically you troll through the selectors in memory looking for the selector text. Thanks Helen Thanks Shadi
gidmanma
@Shadi Almosri: Thanks for the tip! I've updated the link in the answer. Actually, with Opera I never have problems viewing answers on experts exchange. :) But Google cache or Archive.org links should be more accessible, I agree.
Helen
The experts-exchange secret is to just keep scrolling. The answers are there below all their "sign up now!" text.
Hardwareguy
A: 

/* 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<L; i++){
      tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
      if(s.test(tem[0])) SA[SA.length]= tem;
     }
    }
    return SA.join('\n\n');
}

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

the latest item in the cascade is listed first.

kennebec