Site Navigation

Monday, June 28, 2010

bug 391 - IE is strict in setting innerHTML but not appendChild

Issue: #391
Affects: IE6, IE7, IE8, IE9 PP3

IE is well known historically as a browser that doesn't follow the strictness of standards well. IE will often let you do things that you shouldn't be able to do (e.g. add a div to a select element)

However there are cases where IE is very picky - although confusingly arbitrary in how and when it decides to be strict.

Take for example the <p> element. By definition, this is an inline element which means it should not contain block elements.

The following however seems to work fine in all browsers (e.g. the "rule" isn't strictly enforced")


<script type="text/javascript">
var newHeading = document.createElement('h1');
newHeading.appendChild(document.createTextNode('I am an H1 element!'));

However in IE, if you change this to use .innerHTML to set the value IE throws an error.


<script type="text/javascript">
var newString = '<h1>I am an H1 element!</h1>';
try {
myParagraph.innerHTML = newString;
} catch(ex){
alert('Failed: ' + ex['message']);

Which IE then throws an error with the very helpful "Unknown runtime error" message.

This is repeatable for any block level elements: div, h1, h2, h3, h4, h5, h6, blockquote etc.

This obviously isn't desired markup thus the issue with the error is minor however it could well crop up when you adding either content you are not intimately familiar with (JSON response?) or you know the content but are not aware the container element you plan to drop it into is actually an inline element.

Keep this in mind the next time you encounter an "Unknown runtime error" as it might turn out to be a "known issue" ;-)

Known Workarounds: Two. Either ensure you never try to set the innerHTML of an inline element to a block element or use the appendChild() method instead.

Related Issues: None.

Bug/Site Feedback | Submit a bug

No comments: