2012-03-31 34 views
1

使用此代码DOM错误使用JavaScript附加

var html='<div class="somediv"></div>'; 
var target=document.getElementById('contentArea'); 
target.appendChild(html); 

我越来越

Uncaught Error: NOT_FOUND_ERR: DOM Exception 8 
Uncaught TypeError: Cannot call method 'appendChild' of null 

什么建议吗?

+0

这听起来并不令人兴奋。试试:'null.appendChild(“foo”)',注意错误信息,并向后工作。 – 2012-03-31 02:32:44

回答

2

在执行DOM操作时,在获取元素之前,确保已经加载了这些元素。把脚本的底部,就在</body>标记之前应该做

//all other HTML up here 

    <script> 
     var html=document.createElement('div'); 
     html.className = 'somediv'; 
     var target=document.getElementById('contentArea'); 
     target.appendChild(html); 
    </script> 

</body> 

,或者您可以使用window.onload

The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.

window.onload = function() { 
    var html=document.createElement('div'); 
    html.className = 'somediv'; 
    var target=document.getElementById('contentArea'); 
    target.appendChild(html); 
} 
+0

现在我没有得到空错误,只是'未捕获的错误:NOT_FOUND_ERR:DOM异常8' – Luis 2012-03-31 02:17:30

+0

更新了答案。 – Joseph 2012-03-31 02:22:54

+0

嘿,你能最终告诉我一个jQuery prepend()替代javascript吗? – Luis 2012-03-31 02:32:36

3

不能肯定地说,因为您没有提供您选择的DOM,但我猜测您在contentArea元素存在之前正在运行脚本。

如果是这样,请将脚本放置在body元素的末尾。

<head> 
    ... 
</head> 
<body> 
    <div id="contentArea"> 
     ... 
    </div> 

    <script type="text/javascript"> 
     // your script here 
    </script> 
</body> 

或者,只是包装里面的东西:

window.onload = function(){ 
    // your script here 
} 

没有直接关系,但你不应该传递一个HTML字符串appendChild。你应该创建一个DOM节点,然后附加它。

var target=document.getElementById('contentArea'); 
target.appendChild(document.createElement('div')).className = 'somediv'; 
1

var target=document.getElementById('contentArea');无法找到ID为contentArea的元素。你可以发布其他代码吗?

0

运行脚本,我得到了同样的错误Uncaught Error: NOT_FOUND_ERR: DOM Exception 8试图预先准备的数组jQuery对象到DOM元素。我发现该规范允许您预先安排一组DOM元素,但不包含jQuery对象数组。

阅读原因:http://bugs.jquery.com/ticket/11231的详细信息