“Inspect element” is not the same as “View source”

Tools like Firebug for Firefox, WebKit’s Web Inspector and Opera’s Dragonfly are indispensible tools for front-end Web developers, letting you view the DOM as the browser sees it.

And that’s where these tools can actually cause some problems, or at least a bit of confusion. When you choose “Inspect element” or otherwise bring up one your browser’s DOM inspector, what you’re looking at is the document tree after the browser has applied its error correction and after any JavaScripts have manipulated the DOM. It is not necessarily the same as what you see when you choose “View source”.

Take this invalid HTML snippet created by a hypothetical web developer, for example:

  1. <h1>The title</h2>
  2. <p>The first sentence.<strong>The second sentence.</p></strong>

The h1 is closed by an </h2> tag, and the closing strong tag is on the wrong side of the closing p tag. Two mistakes that can happen when you’re typing HTML by hand. This is what you will see when you view source in your browser. But what if you bring up a developer tool?

Firebug/Firefox

Firebug tells you that the DOM looks like this in Firefox:

  1. <h1>The title</h1>
  2. <p>The first sentence.<strong>The second sentence.</strong></p>
  3. <strong></strong>

Hmm. Where did the </h2> tag go? And how did the </strong> tag end up in the right place? Error correction.

Web Inspector/Safari

What about the Web Inspector in Safari then? It shows this:

  1. <h1>The title
  2. <p>The first sentence.<strong>The second sentence.</strong></p>
  3. <strong></strong>
  4. </h1>

Whoa! Everything is in the h1? Not what the source HTML says, and not the same as Firefox either. Again, error correction.

Dragonfly/Opera

Ok, let’s take a look in one more tool, Opera Dragonfly:

  1. <h1>The title</h1>
  2. <p>
  3. The first sentence.
  4. <strong>The second sentence.</strong>
  5. </p>

Hey, that looks just like what the hypothetical developer probably intended to write. Yet another example of error correction.

Different browsers have different DOMs

Note that the DOM is different in all three browsers.

There are two lessons to be learned from this:

  1. DOM inspectors are not “View source”
  2. Browsers use different error correction (at least until they all fully support HTML5), which is one of the reasons Validation matters.

Posted on September 30, 2010 in (X)HTML, Browsers

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.