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

I am trying to populate a DOM element with the identifier 'myElement'. The content I fill is a combination of text and HTML elements.

Suppose the following content that I want 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 shredding the last word in my sentence. Apparently, the problem is related to the '&' character present in the last word. I played with '&' and innerHTML, and the following are my observations.

  • If the last word of the content is less than 10 characters, and if it has a '&' character present in it, innerHTML breaks the sentence into '&'.
  • This problem does not occur in firefox.
  • If I use innerText, the last word is in tact, but then all the HTML tags that are part of the content become plain text.

I tried to populate the jQuery #html method,

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

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

How can I paste HTML content with the last word containing '&' without clipping it in all browsers?

Update : 1. I tried html coding of the content that I am trying to insert into the DOM. When I encode the content, the html tags that are part of the content become a simple string.

For the above content, I expect the result to display as

Success is hard work and luck

but when I encode what I really get on the displayed page,

<b>Success</b> is a matter of hard work &luck

+3
3

& &amp;.

& () HTML . , &quot; = ", &lt; = <, etcetera. &luck HTML ( ). , - ( ) , HTML (&, ) .

&luck; HTML, . - HTML &amp;.

. , . PHP, , htmlentities . , <script>.

+5

HTML , :

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

:

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

By ampersand's HTML encoding, you warrant that there is no ambiguity in what you mean when you write & luck.

0
source

Source: https://habr.com/ru/post/1739447/


All Articles