Summary: This function returns an ordered list of all duplicate class names that can be easily used to combine classes.
To get started, select a useful list of duplicates:
var multi = {}; $("*[class]").each(function(){ var class = this.className.replace(/^\s+|\s+$/g,"").replace(/\s+/g,"."); if(!/\./.test(class)) return;
Execute my function and output the variable array_multi . This will show you a map of several class names so that you can replace multiple classes accordingly.
Due to the special way I saved the class names, you can use $("." + array_multi[n][0]) to access all elements that have a set of class names that is equal to the set as described in the nth positions in array_multi .
Example of readable output:
//Overwrites current document! var list = ""; for(var i=0; i<array_multi.length; i++) list += array_multi[i][0] + "\t" + array_multi[i][1]; document.open(); document.write("<pre>"+list+"</pre>") document.close();
Automatic conversion
A way to automate merging i classes by adding all the individual properties of a class to a JavaScript string and adding it to an object. This is the most reliable way to get the exact properties of CSS, because trying to get cool names through the document.styleSheets object may give slightly different results. Example:
var classStyle = {}; classStyle["class1"] = "border:1px solid #000;"; classStyle["class2"] = "color:red"; //Make sure that each declaration ends with a semicolon: for(var i in classStyle) if(!/;$/.test(classStyle[i])) classStyle[i] += ";"; //Initialise var all_styles = {}; for(var i=0; i<array_multi.length; i++){ all_styles[array_multi[i][1]] = ""; } //This loop takes definition precedence into account for(var currentCName in classStyle){ var currentClass = new RegExp("(?:^|\\.)" + currentCName + "(?:\\.|$)"); // Rare occasion of failure: url("data:image/png,base64;....") var separateProps = classStyle[currentCName].split(";"); var prop_RE = {}; for(var p=0; p<separateProps.length; p++){ var cssProperty = separateProps[p]; if(!/:/.test(cssProperty)) continue; //Invalid CSS property prop_RE[cssProperty] = new RegExp("(^|;)\\s*" + cssProperty.match(/(\S+)\s*:/gi)[1] + "\\s*:[^;]+;?", "gi"); } for(var class in all_styles){ if(currentClass.test(class)){ for(var k in prop_RE){ all_styles[class] = all_styles[class].replace(prop_RE[k],"$1") + k; } } } } //To finish off: var allClassesToString = ""; for(var class in all_styles){ var newClass = class.replace(/\./g, "_"); $("."+class).each(function(){ this.className = newClass; }); allClassesToString += "."+newClass + "{" + all_styles[class] + "}\n"; } // allClassesToString <------- This variable now holds a string of all duplicate CSS classes! //Example: var style = $("<style>"); style.text(allClassesToString); style.appendTo($("head:first"));
source share