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:
But try the same code in IE and you get a very different result:
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.