Odd jQuery gotcha: IE and .html()

Apr 30 2008

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:

<div>
<button id="test">What is the magic number?</button>
</div>

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 an odd example of what can happen if you’re not careful about browser testing your scripts as well as your HTML and CSS.

Filed under: Javascript.

Technorati tags:

Digg this article

Bookmark this article with del.icio.us

Previously: Is it time to re-introduce sound to the web?

Next: Relaunched freelance site


Comments

Comment form

Comment form (not displayed, Gravatar-enabled) Remember this is not Spam.

Live Preview

: