Pelicans Are Evil

22 August, 2006
 

innerHTML and Internet Explorer

Jagshemash!

There is a "bug" in IE that will stop innerHTML working when you insert data that contains block tags. I have read on other forums that its caused by inserting block tags into inline tags (which is not actually an error as you shouldn't insert block tags into inline tags. It's not valid XHTML). However I had a problem where I was using ajax to obtain code for a html table, then inserting that table into a div tag using innerHTML.

When I tested my ajax in IE, I got a runtime error. After hours of thinking it was my ajax I discovered that it was caused by innerHTML.

Lets take a look at an example shall we?
var div_tag = document.getElementById('div_tag');
div_tag.innerHTML = '<table><tr><td>Hi there</td></tr></table>';



Now your probally thinking that the previous code should work in IE. Well it doesn't. IE will kick you to the curb with a runtime error if you tried that. It's because IE (in all its wisdom) does not like you!

However its pretty easy to get around, just a few extra steps are needed!

var tmp_tag = document.createElement('div');
var div_tag = document.getElementById('div_tag');
tmp_tag.innerHTML = '<table><tr><td>Hi there</td></tr></table>';
div_tag.appendChild(tmp_tag);



This basically creates a new div tag (via createElement), adds the html into that tag and appends that tag into the span tag.

This works in both IE & FireFox.
Enjoy.
 
Comments: Post a Comment



Links to this post:

Create a Link



<< Home