Fix Inserted HTML5 Content with HTML5 innerShiv

Published by Chris Coyier

When working with HTML5 today, many of you know that you'll need to include the "HTML5 shiv" to ensure that CSS will recognize and be able to style those elements in browsers that aren't yet hip to HTML5.

<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

Credit for that to Remy Sharp, Jon Neal, John Resig and anybody else who contributed to that idea. Also for the benefit of those non-hip browsers, it's best to reset many of the HTML5 elements to block-level as they should be:

article, aside, figure, footer, header, hgroup,
menu, nav, section { display: block; }

Now we're all set to use and style HTML5 elements. But wait! What happens if we dynamically add HTML5 to the page via JavaScript.

var s = document.createElement('div');
s.innerHTML = "<section>Hi!</section>";
document.body.appendChild(s);

Or in jQuery:

$("body").append("<section>Hi!</section>");

Hip browsers do fine, but Internet Explorer will once again not recognize the new element and not apply CSS to it.

Joe Bartlett has written a great work-around to the problem called HTML5 innerShiv and I thought more people should be aware of it.

Update January 2013: This is now included in the canonical html5shiv project, you should use that. The rest of this project is a bit outdated. You don't need to do it this way anymore if you use the html5shiv.

Using it

Please note that this script does not require jQuery. It's just vanilla JavaScript and will work with any library or library at all.

1. Download

Download the script and insert it onto your page. Or copy and paste the script into other JavaScript you are already loading if you want to avoid an extra HTTP Request.

2. Wrap all HTML content in innerShiv function before inserting

Here is the same jQuery example as above, made to work using innerShiv:

$("body").append(innerShiv("<section>Hi!</section>"));

Quick demo.