Tuesday, 12 July 2011

jQuery's .html() and Internet Explorer 8

Sometimes it's easy to blame IE for unwanted behaviour. This case is a bit different, in the sense that I think IE's behaviour is understandable, or even correct. I was trying to fix a bug where the contents of an overlay screen would not load in IE8. The contents were fetched using an ajax GET request, after which this piece of code would be executed:

show: function(html) {
  var box = $("#dialog_box");  

In Firefox or Chrome, this works fine. I verified that the show method was actually called with the html from the GET request. The box.show() call was executed correctly, but somehow the box.html(html) was not. But the method didn't fail either.

After much fiddling around, I've found out that:

Internet Explorer will only insert a HTML string using jQuery's .html() method if every tag in the HTML string is opened and closed properly.

The response from the GET request wasn't valid, it contained one closing div tag too many. IE then refuses to insert the HTML into the DOM. Other browsers seem to have no problem inserting the invalid HTML. So IE8 is correct? Remarkable.


  1. Thought I'd leave a note for anyone else that stumbles across your blog. I have been having the same issue and even after making sure the jQuery.get response was valid IE<=8 just wasn't playing ball. I'm not 100% on the intricacies of how jQuery works it's magic but I'm still convinced that this where the issue lies as I ended up reverting to the tried and tested:

    document.getElementById('foo').innerHTML = data;

    ... which does work cross-browser.

  2. I was having the same issue. Myles work around really helped me here.