Here’s something interesting I came across while reading Introducing HTML5 by Bruce Lawson and Remy Sharp, which I recently purchased.
In one of the early chapters, Bruce mentions that when tags are not nested properly, the resulting generated DOM will be seen differently in different browsers. Of course, when you “view source”, the code will be the same in all browsers. It’s when you inspect the page (or view the “generated source”) using developer tools that the results can differ.
After some testing, this is indeed the case. Here’s the code that I tested:
<div> <p><span><b>This is some text</span></b></p> </div>
If you want to test it yourself, just throw that snippet into a valid HTML document inside the
<body> tag. Here’s a demo page if you want to use my example.
You’ll notice that the tags inside the paragraph element are nested incorrectly; that is, the
<span> tag opens, followed by an opening
<b> element, but then when those tags are closed, the
<span> element is closed first.
This is essentially code validation 101, so generally speaking, you shouldn’t ever do this when hand coding. Not to mention the fact that most good code editors will close tags automatically–and correctly–so you shouldn’t see this too often, if ever.
Nonetheless, for reasons I’ll get into below, you should be aware of how the DOM looks to a browser that sees this mistake. Here are some screen shots of different browsers viewing the DOM through their respective web developer tools:
Internet Explorer 9 Beta
As you can see from the five examples shown above, the DOM, which is built by the browser’s rendering engine, appears differently in some browsers.
Full Double Bold Element! What Does it Mean?
It almost looks like a triple bold element! Okay enough of that.
Another key factor here (and the reason why Bruce mentions it in Introducing HTML5), has to do with the goal of interoperability for web languages. The HTML5 spec includes instructions to browser makers to tell them how to handle errors in markup. This way, problems like incorrectly nested tags are rendered the same way in each browser, thus avoiding cross-browser surprises for developers.
Firefox 3.6, IE9, and Safari 5 all display an extra element. Also, they are the most recent versions of those browsers, so it seems strange that they have different results from the others (especially Safari vs. Chrome since they’re both built on WebKit). If the browser makers are supposed to display incorrect markup the same way, then why are there differences in these examples?
If you can think of any other problems this could cause, or anything significant I’ve left out, feel free to comment.