Odd jQuery gotcha: IE and .html()

posted 30th April 2008 11:05

Here’s an odd one.

If you use jQuery’s .html() method to find a string of HTML, beware if that HTML contains any elements that have events registered—you might get a little more than you bargained for.

Here’s a simple test case:

And the JavaScript to attach an event to the button that alerts the HTML contained in its parent element (the div):

$('#test').click(function () {
var x = $(this).parent().html();
alert(x);
});

Run the code in Firefox, and you get the expected result—the HTML contained within the div:

Alert in Firefox, showing HTML text

But try the same code in IE and you get a very different result:

Alert in IE, showing random number

What’s that all about, then? Given that I was trying to parse a number out of the content, this behaviour threw a rather large spanner in the works.

The alternative, if you don’t strictly need the tags, is to use .text() instead—but it’s still weird.

« The Watchmaker Project