Is there a way to determine whether or not a css class exists using JavaScript?
if ($(".class-name").length > 0) {
}
That is a nice way to check the class in HTML by using javascript
/* 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.
You could check and see if an object of the style your are looking for already exists. If it does then the css class must exist because an object is using it. For example if you wanted to make sure that distinctly named svg objects each have their own style:
function getClassName(name) {
//Are there any elements which use a style named 'name' ?
if (document.getElementsByClassName(name).length === 0){
//There are none yest, let's make a new style and add it
var style = document.createElement('style');
style.type = 'text/css';
//Where you might provide your own hash function or rnd color
style.innerHTML = '.'+name+' { fill: #' + getHashColor(name) + '; background: #F495A3; }';
//Add the style to the document
document.getElementsByTagName('head')[0].appendChild(style);
}
return name;
}
Note that this is NOT a good approach if you are looking for a style which isn't necessarily used in your document.
function getAllSelectors() {
var ret = [];
for(var i = 0; i < document.styleSheets.length; i++) {
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
for(var x in rules) {
if(typeof rules[x].selectorText == 'string') ret.push(rules[x].selectorText);
}
}
return ret;
}
function selectorExists(selector) {
var selectors = getAllSelectors();
for(var i = 0; i < selectors.length; i++) {
if(selectors[i] == selector) return true;
}
return false;
}