How to find classes that are not used in any CSS selector?
Consider the following HTML snippet on a page:
<style type="text/css"> .existing-class { background-color: #000; } </style> <div class="existing-class non-existing-class"></div> It has 2 classes. Here's what: non-existing-class not defined anywhere in the CSS available on the page, however the div uses it.
My question is: how can a developer programmatically detect elements on a page that use classes that are not actually defined in the loaded CSS?
Ok, there you go;)
Take a look at the generated script, especially getUndefinedClasses .
function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open( "GET", theUrl, false ); // false for synchronous request xmlHttp.send( null ); return xmlHttp.responseText; } function getAllCSSClasses(cssdata) { var re = /\.(.+)\{/g; var m; let classes = []; do { m = re.exec(cssdata); if (m) { for(let key in m) { if( (typeof m[key] == "string") && (classes.indexOf(m[key]) == -1) && (m[key].indexOf(".") == -1) ) classes.push(m[key].replace(/\s/g, " ")); } } } while (m); return classes; } function getAllClasses() { var csses = document.querySelectorAll('link[rel="stylesheet"]'); var classes = [] for (i = 0; i < csses.length; ++i) { // let styledata = httpGet(csses[i].href); var styledata = ".hi{ display: none; }"; var cclasses = getAllCSSClasses(styledata); var classes = Object.assign([], classes, cclasses); classes.concat(cclasses); } return classes; } function getHTMLUsedClasses() { var elements = document.getElementsByTagName('*'); var unique = function (list, x) { if (x != "" && list.indexOf(x) === -1) { list.push(x); } return list; }; var trim = function (x) { return x.trim(); }; var htmlclasses = [].reduce.call(elements, function (acc, e) { return e.className.split(' ').map(trim).reduce(unique, acc); }, []); return htmlclasses; } function getUndefinedClasses(cssclasses, htmlclasses) { var undefinedclasses = []; for (let key in htmlclasses) { if(cssclasses.indexOf(htmlclasses[key]) == -1 ) { undefinedclasses.push(htmlclasses[key]); } } return undefinedclasses; } var cssclasses = getAllClasses(); var htmlclasses = getHTMLUsedClasses(); console.log("Undefined classes : " + getUndefinedClasses(cssclasses, htmlclasses)) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>JS Bin</title> <link rel="stylesheet" href="hi there"> </head> <body> <div class="hi"></div> <div class="there"></div> <div class="there_thier_333"></div> </body> </html> What is done:
- I get all the cool names from css data (you can pass css data in various ways).
- Then I get all the classes used in the HTML elements, both of which are written to arrays.
- Finally, I just click on the classes that were used by HTML Elements but not found in the cssclasses array, which leaves you with undefined classes in CSS.