Question

I'm having a weird issue in IE when I set an elements innerHTML attribute to a string that contains a script element.

What happens is, when innerHTML is set like:

domEl.innerHTML = "<script type=\"text/javascript\">alert(\"hello world\");</script>"
alert(domEl.innerHTML);

The alert box doesn't show any text, as if the script element was removed completely. In addition, checking the element's childNodes collection also shows that the script element is not present as domEl.childNodes.length = 0.

However, if you add some text before the script tag like so:

domEl.innerHTML = "start text<script type=\"text/javascript\">alert(\"hello world\");</script>"
alert(domEl.innerHTML);

The script element is present when the alert box is shown.

Why is this happening and how can I fix it properly? Is this a bug in IE? It works fine in the latest versions of Chrome and Firefox. I'm using IE 8 for this.

Était-ce utile?

La solution

looks like a bug, or some weird security consideration in IE. try using XMP tags around your text. it might work, but that depends on what you were trying to achieve.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top