Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using appendChild with IE in Javascript

I am having trouble 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 I get in Internet Explorer (IE9) is: "unexpected call to a method or access to a property" on statement "_js.appendChild(textNode)".

Is there any way to work around this problem?

like image 804
Mike Avatar asked Aug 17 '11 08:08

Mike


1 Answers

As you can see here appendChild() in IE is not applied to <script>-elements. (Seems as if IE9 supports it, but it depends on the browser-mode)

There was an correct answer before by Nivas, unfortunately it has been deleted. In IE use

_js.text = scriptContent; 
like image 115
Dr.Molle Avatar answered Sep 20 '22 07:09

Dr.Molle