Using appendChild with IE in Javascript

I am having problems with this code in IE (with Chrome, it seems to work fine):

<html> <body> <script type="text/javascript"> var scriptContent = "var whatever=1"; var _js = document.createElement('script'); _js.setAttribute('type', 'text/javascript'); textNode = document.createTextNode(scriptContent); _js.appendChild(textNode); document.getElementsByTagName('body')[0].appendChild(_js); </script> </body> </html> 

The error that I get in Internet Explorer (IE9) is: "unexpected method call or property access" in the instruction "_js.appendChild (textNode)".

Is there any way around this problem?

+6
source share
2 answers

As you can see here appendChild() in IE does not apply to <script> elements. (IE9 seems to support it, but depends on browser mode)

Prior to that, Nivas had the correct answer, unfortunately it was deleted. In IE use

 _js.text = scriptContent; 
+4
source

Your script is executed before the DOM is ready, so getting the <body> is a race condition. I really get the same error in Chrome 15 and Firefox 8.

You can see the works code when called after loading the page, for example, in a function

HTML

 <a href="#" onclick="return append()">append</a> 

Javascript

 function append() { var scriptContent = "var whatever=1"; var _js = document.createElement('script'); _js.setAttribute('type', 'text/javascript'); textNode = document.createTextNode(scriptContent); _js.appendChild(textNode); document.getElementsByTagName('body')[0].appendChild(_js); return false; } 
+3
source

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


All Articles