tags:

views:

128

answers:

5

Is there a tool that will find for me all the css classes that I am referencing in my HTML that don't actually exist?

ie. if I have <ul class="topnav" /> in my HTML and the topnav class doesn't exist in any of the referenced CSS files.

This is similar to SO#33242, which asks how to find unused CSS styles. This isn't a duplicate, as that question asks which CSS classes are not used. This is the opposite problem.

A: 

Visual Studio 2008 SP 1 :)

dimarzionist
+1  A: 

Error Console in Firefox. Although, it gives all CSS errors, so you have to read through it.

Milan Babuškov
A: 

IntelliJ Idea tool does that as well.

Swati
+3  A: 

You can put this JavaScript in the page that can perform this task for you:

function forItems(a, f) {
  for (var i = 0; i < a.length; i++) f(a.item(i))
}

function classExists(className) {
  var pattern = new RegExp('\\.' + className + '\\b'), found = false

  try {
    forItems(document.styleSheets, function(ss) {
      // decompose only screen stylesheets
      if (!ss.media.length || /\b(all|screen)\b/.test(ss.media.mediaText))
        forItems(ss.cssRules, function(r) {
          // ignore rules other than style rules
          if (r.type == CSSRule.STYLE_RULE && r.selectorText.match(pattern)) {
            found = true
            throw "found"
          }
        })
    })
  } catch(e) {}


  return found
}
mislav
great code snippet! I just grabbed this to help me find CSS classes referenced that don't exist. Of course the trouble is that sometimes the class attribute is "overloaded" to provide a JavaScript hook ;-) but now I can at least see which ones have no styling applied. Awesome!
scunliffe
A: 

This Firefox extension is does exactly what you want:

http://www.sitepoint.com/dustmeselectors/

It locates all unused selectors.

Buzz
This is not the problem I'm trying to solve, I want to find all class attributes in the HTML that don't correspond to class names in the CSS.
Deeksy
Agree with @Deeksy - I too grabbed dustmeselectors once... but it would flag stuff that was defined, but used elsewhere on my site. Thus you need to aggregate a bunch of data from multiple pages to ensure you truly have a "dead" selector. @mislav's answer is bang on.
scunliffe