Using appendChild with IE in Javascript

前端 未结 2 1182
南笙
南笙 2020-12-20 15:42

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





        
相关标签:
2条回答
  • 2020-12-20 16:00

    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; 
    
    0 讨论(0)
  • 2020-12-20 16:12

    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;
    }
    
    0 讨论(0)
提交回复
热议问题