2012-03-31 18 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的詳細信息