Maison >interface Web >tutoriel CSS >Détecter les classes inutilisées dans ... HTML

Détecter les classes inutilisées dans ... HTML

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌original
2025-03-23 09:28:11451parcourir

Detect Unused Classes in... HTML

Usually, when “unused” comes up in conversation regarding CSS, it’s about removing chunks of CSS that are not used in your site or, at least, the styles not currently in use on a specific page. The minimal amount of CSS is best! I’ve written about how this is a hard problem in the past. In JavaScript-land, the equivalent is tree shaking (removing unusued JavaScript).

But what about the other way around, detecting classes in HTML that aren’t used in your CSS? If you knew this for sure, you could clean up your markup, removing classes that don’t do anything.

I saw Robert Kieffer post a Gist the other day with an interesting solution. The idea is to load up document.styleSheets and find all the rules (the ones that are classes). Then, use a MutationObserver to watch the DOM for all HTML, and check the classList of each node to see if it matches any from any stylesheet. If the HTML has a class not found in a stylesheet, report it.

I gave it a quick whirl and got it working and correctly reporting unused classes:

Your mileage may vary. For one thing, this script is set up as an ES Module. That means if you just import it and run it on a regular ol’ HTML document, it won’t find anything because your