IE innerHTML chops sentence if the last word contains '&' (ampersand)

Posted by Mandai on Stack Overflow See other posts from Stack Overflow or by Mandai
Published on 2010-04-01T10:19:31Z Indexed on 2010/04/01 10:23 UTC
Read the original article Hit count: 609

Filed under:
|
|
|

I am trying to populate a DOM element with ID 'myElement'. The content which I'm populating is a mix of text and HTML elements.

Assume following is the content I wish to populate in my DOM element.

var x = "<b>Success</b> is a matter of hard work &luck";

I tried using innerHTML as follows,

document.getElementById("myElement").innerHTML=x;

This resulted in chopping off of the last word in my sentence. Apparently, the problem is due to the '&' character present in the last word. I played around with the '&' and innerHTML and following are my observations.

  1. If the last word of the content is less than 10 characters and if it has a '&' character present in it, innerHTML chops off the sentence at '&'.
  2. This problem does not happen in firefox.
  3. If I use innerText the last word is in tact but then all the HTML tags which are part of the content becomes plain text.

I tried populating through jQuery's #html method,

 $("#myElement").html(x);

This approach solves the problem in IE but not in chrome.

How can I insert a HTML content with a last word containing '&' without it being chopped off in all browsers?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about innerhtml