Home

Awesome

HTML Inspector

:warning: NOTE: I no longer have time to maintain this project, respond to issues, or address PRs. If anyone else would like to take over as a maintainer, please contact me.


  1. Getting Started
  2. Configuring HTML Inspector
  3. Built-in Rules
  4. Writing Your Own Rules
  5. Overriding Rules Configurations
  6. Browser Support
  7. Running the Tests
  8. Contributing
  9. FAQs
  10. Third Party Rules

HTML Inspector is a highly-customizable, code quality tool to help you (and your team) write better markup. It aims to find a balance between the uncompromisingly strict W3C validator and having absolutely no rules at all (the unfortunate reality for most of us).

HTML Inspector is opinionated, but every rule is completely customizable, so you can take what you like and change what you don't. It's also easy to extend, allowing teams to write their own rules to enforce their chosen conventions.

For a more formal introduction, please refer to this blog post which goes into more detail as to why HTML Inspector was created and why you should consider using it.

Getting Started

The easiest way to try out HTML Inspector is to link to the source file hosted on CDNJS:

<script src="http://cdnjs.cloudflare.com/ajax/libs/html-inspector/0.8.2/html-inspector.js"></script>

It can also be installed via NPM or Bower:

# NPM (for command line usage)
npm install -g html-inspector

# Inspect a file from the command line
# Note: the CLI requires phantomjs to be installed
# http://phantomjs.org/download.html
htmlinspector path/to/file.html

# View the CLI options
htmlinspector --help

# Bower (for browser usage)
bower install html-inspector

If you clone the Github repo, just use the file named html-inspector.js in the project root.

Once HTML Inspector is added, you can run HTMLInspector.inspect() to see the results. Calling inspect with no options will load all rules and run them with their default configuration options.

<script src="path/to/html-inspector.js"></script>
<script> HTMLInspector.inspect() </script>

After the script runs, any errors will be reported to the console (unless you change this behavior). Here's an example of what you might see:

Sample HTML Inspector Output

Make sure you call inspect after any other DOM-altering scripts have finished running or those alterations won't get inspected.

Configuring HTML Inspector

By default, HTML Inspector runs all added rules, starts traversing from the <html> element, and logs errors to the console when complete, but all of this can be customized.

The inspect method takes a config object to allow you to change any of this behavior. Here are the config options:

Here are the default configuration values:

config: {
  domRoot: "html",
  useRules: null,
  excludeRules: null,
  excludeElements: "svg",
  excludeSubTrees: ["svg", "iframe"],
  onComplete: function(errors) {
    errors.forEach(function(error) {
      console.warn(error.message, error.context)
    })
  }
}

Here is how you might override the default configurations:

HTMLInspector.inspect({
  domRoot: "body",
  excludeRules: ["some-rule-name", "some-other-rule-name"],
  excludeElements: ["svg", "iframe"],
  onComplete: function(errors) {
    errors.forEach(function(error) {
      // report errors to external service...
    })
  }
})

For convenience, some of the config options may be passed as single arguments. If .inspect() receives an argument that is an array, it is assumed to be the useRules option; if it's a string or DOM element, it's assumed to be the domRoot option; and if it's a function, it's assumed to be the onComplete callback.

// only set the useRules options
HTMLInspector.inspect(["some-rule-name", "some-other-rule-name"])

// only set the domRoot
HTMLInspector.inspect("#content")

// only set the onComplete callback
HTMLInspector.inspect(function(errors) {
  errors.forEach(function(error) {
    // report errors to an external service...
  })
})

Built-in Rules

HTML Inspector ships with a set of built-in rules that fall into one of three main categories: validation, best-practices, and convention.

Each rule is registered via a unique string identifier that can be used to include or exclude it at inspection time.

Here is the full list of built-in rules by their identifiers:

# validation rules
validate-elements
validate-element-location
validate-attributes
duplicate-ids
unique-elements

# best-practices
inline-event-handlers
script-placement
unused-classes
unnecessary-elements

# convention
bem-conventions

The following is a more in-depth explanation of each rule:

Validation

HTML Inspector is different than a markup validator. Validators parse static markup, while HTML Inspector runs on a live DOM. This makes it a lot more powerful, but there are some drawbacks as well. Because HTML Inspector runs after the browser has parsed your HTML, any mistakes the browser has forgiven will not be seen by HTML Inspector.

As a result HTML Inspector should not be seen as a replacement for validation.; it's simply another tool in the toolbox. That being said, there is still a lot that it can do (and does) to validate your markup.

Here are the validation rules that ship with HTML Inspector. (Expect this list to get more comprehensive in the future.)

Best Practices

Some markup may be perfectly valid but uses practices that are commonly considered to be poor or outdated. The following rules check for these types of things. (Note that everything in this list is subjective and optional.)

Convention

The real power of HTML Inspector lies in its ability to enforce your team's chosen conventions. If you've decided that all groups of links should be contained in a <nav> element, or all <section> elements must contain a heading, you can write those rules and an error will be thrown when someone breaks them.

Because conventions are usually specific to individual teams, there's only one built-in rule in this category, but hopefully it'll get you thinking about rules your team could use.

Writing Your Own Rules

Rules are the bread and butter of HTML Inspector. They are where you check for problems and report errors.

Here's how you add new rules:

HTMLInspector.rules.add(name, [config], func)

Events

The listener object can subscribe to events via the on method. Like with many other event binding libraries, on takes two parameters: the event name, and a callback function:

listener.on(event, callback)

Here is an example of binding a function to the "class" event:

listener.on("class", function(className, domElement) {
  if (className == "foo" and element.nodeName.toLowerCase() == "bar") {
    // report the error
  }
})

Below is a complete list of events along with the arguments that are passed to their respective handlers. For events that occur on a DOM element, that element is passed as the final argument. It is also bound to the this context.

Reporting Errors

When you find something in the HTML that you to want warn about, you simply call the warn method on the reporter object.

reporter.warn(rule, message, context)

Here's an example from the validate-elements rule:

reporter.warn(
  "validate-elements",
  "The <" + name + "> element is not a valid HTML element.",
  element
)

An Example Rule

Imagine your team previously used the custom data attributes data-foo-* and data-bar-*, but now the convention is to use something else. Here's a rule that would warn users when they're using the old convention:

HTMLInspector.rules.add(
  "deprecated-data-prefixes",
  {
    deprecated: ["foo", "bar"]
  },
  function(listener, reporter, config) {

    // register a handler for the `attribute` event
    listener.on('attribute', function(name, value, element) {

      var prefix = /data-([a-z]+)/.test(name) && RegExp.$1

      // return if there's no data prefix
      if (!prefix) return

      // loop through each of the deprecated names from the
      // config array and compare them to the prefix.
      // Warn if they're the same
      config.deprecated.forEach(function(item) {
        if (item === prefix) {
          reporter.warn(
            "deprecated-data-prefixes",
            "The 'data-" + item + "' prefix is deprecated.",
            element
          )
        }
      })
    }
  )
})

Overriding Rule Configurations

Individual rules may or may not do exactly what you need, which is why most rules come with a configurations object that users can customize. A rule's configuration can be changed to meet your needs via the extend method of the HTMLInspector.rules object.

HTMLInspector.rules.extend(rule, overrides)

Here are two examples overriding the "deprecated-data-prefixes" rule defined above. The first example passes an object and the second passes a function:

// using an object
HTMLInspector.rules.extend("deprecated-data-prefixes", {
  deprecated: ["fizz", "buzz"]
})

// using a function
HTMLInspector.rules.extend("deprecated-data-prefixes", function(config) {
  return {
    deprecated: config.deprecated.concat(["bazz"])
  }
})

Here are a few more examples. The following override the defaults of a few of the built-in rules.

// use the `inuit.css` BEM naming convention
HTMLInspector.rules.extend("bem-conventions", {
  methodology: "inuit"
})

// add Twitter generated classes to the whitelist
HTMLInspector.rules.extend("unused-classes", {
  whitelist: /^js\-|^tweet\-/
})

Browser Support

HTML Inspector has been tested and known to work in the latest versions of all modern browsers including Chrome, Firefox, Safari, Opera, and Internet Explorer. It will not work in older browsers that do not support ES5 methods, the CSS Object Model, or console.warn(). Since HTML Inspector is primarily a development tool, it is not intended to work in browsers that aren't typically used for development and don't support modern Web standards.

If you need to test your site in older versions of IE and don't want to see JavaScript errors, simply wrap all your HTML Inspector code inside a conditional comment, so it is ignored by IE9 and below. Here is an example:

<!--[if gt IE 9]><!-->
  <script src="path/to/html-inspector.js"></script>
  <script>HTMLInspector.inspect()</script>
<!--<![endif]-->

Running the Tests

If Grunt and all the dependencies are installed, you can run the tests with the following command.

grunt test

HTML Inspector has two test suites, one that runs in pure Node and one that uses Mocha and PhantomJS because it needs a browser.

If you want to run the browser tests in a real browser (instead of via PhantomJS) simply fire up a local server and load the tests/html-inspector-test.html file. Make sure to run grunt test beforehand as it builds the tests.

Contributing

I'm always open to feedback and suggestions for how to make HTML Inspector better. All feedback from bug reports to API design is quite welcome.

If you're submitting a bug report, please search the issues to make sure there isn't one already filed.

If you're submitting a pull request please read CONTRIBUTING.md before submitting.

FAQs

The FAQs section has grown rather large, so it has been moved to its own page. You can find the full FAQs here.

Third Party Rules