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?

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. Commented Aug 17, 2011 at 9:05

2 Answers 2

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; 
Sign up to request clarification or add additional context in comments.

Comments

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;
}

3 Comments

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 ready
I think the problem for the appendChild is not for the body, but for the script tag.
@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 :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.