Using appendChild with IE in Javascript
Asked Answered
B

2

9

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?

Brazee answered 17/8, 2011 at 8:58 Comment(1)
From what I've read, IE9 has some issues using appendChild to the body element (i know your error is before this). Ideally you want to be putting your scripts into the head anyway, not the body.Macao
S
5

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; 
Swatter answered 17/8, 2011 at 10:7 Comment(0)
I
3

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

You can see the code works when called after the page is loaded, 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;
}
Industrials answered 17/8, 2011 at 9:6 Comment(3)
Yes, the question was about getting it working in IE9, which I tested and it works (but I totally agree it depends on which browsing mode). I believe my answer is still valid with regards to the DOM not ready part, since I get exactly the same error in different browsers without calling the append after the DOM is readyIndustrials
I think the problem for the appendChild is not for the body, but for the script tag.Dirk
@andyb:I guess IE9 has been the used browser, but the OP likes to get it work in earlier versions too(there are still a lot of WinXP-users where IE9 is unavailable). But of course your answer is still valid and also good :)Swatter

© 2022 - 2024 — McMap. All rights reserved.