Is there a way or tool available for detecting unused class names in HTML code?
I have some HTML code with old Bootstrap, jQuery, and personalized CSS styles like below:
<div class="clear fot-her likes tab-sub">content</div>
But I need to identify and remove any unused classes. If the fot-her
class does not apply any style, I want to add it to a list and display an alert.
I found this, but it only retrieves the element's computed style:
var style = window.getComputedStyle(element [, pseudoElt]);
And this fetches elements by class name only:
var elements = document.getElementsByClassName(names);
Script:
function checkClassCSS() {
let doc = document.all;
let style = document.styleSheets;
var listOfClasses = []
Object.entries(doc).forEach(([key, element]) => {
let classes = element.className.split(/\s+/);
let new_classes = []
classes.forEach((cl) => {
if (cl != '') {
new_classes = new_classes.concat(['.' + cl]);
}
});
listOfClasses = listOfClasses.concat(new_classes);
});
listOfClasses = listOfClasses.filter(v => v != '');
listOfClasses = Array.from(new Set(listOfClasses));
var selectorClass = []
Object.entries(style).forEach(([key, node]) => {
let rule = node.cssRules;
Object.entries(rule).forEach(([key, cssSelector]) => {
selectorClass = selectorClass.concat([cssSelector.selectorText]);
});
});
selectorClass = selectorClass.filter(v => v != '');
selectorClass = Array.from(new Set(selectorClass));
var missing = [];
listOfClasses.filter(function(x) {
if (!selectorClass.includes(x)) {
missing.push(x);
}
})
console.log(missing);
}
I am having trouble correctly identifying unused class names. For example, col-lg-4
may be used in the HTML code but still appears in the missing
variable.