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
<script type="module"> is deferred and the
MutationObserver won’t pick anything up. I just un-moduled it and put it in the
<head> to make my demo work.
I Netlify Dropped the site online in case you wanna dig into it and check it out. I would have used CodePen, but CodePen doesn’t link up your styles as
<link>ed stylesheets (by default, but you could use external resources to do that). I just thought it would be more clear as a deployed site.
<style> blocks, which this script wouldn’t check. Heck, you might have integration tests that run in CI that use classes to do testing-related things.
I’d say this kind of thing is a useful tool for havin’ a looksie at classes that you have a hunch might be unused. But I wouldn’t say there’s a permission slip to run this thing and then yank out every reported class without further investigation.
The post Detect Unused Classes in… HTML appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.