2016-12-16 29 views
3

嘿,我想提出一個網站,只是JavaScript,但我得到這個錯誤:JavaScript的網站錯誤:未捕獲的類型錯誤:無法執行「的appendChild」的「節點」

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'at html:12:9 

這裏是我的html代碼:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
</head> 
<body> 

    <script> 
     var divEl = document.createElement("div"); 
     document.body.appendChild(divEl); 
     var ptag = document.createElement("p").setAttribute("id", "lol"); 
     divEl.appendChild(ptag); 

    </script> 

</body> 
</html> 
+5

'document.createElement(「p」)。setAttribute(「id」,「lol」);'不返回節點。 – vlaz

回答

3

setAttribute不返回一個節點,以便您的ptag變量是越來越設置爲undefined

doc

Adds a new attribute or changes the value of an existing attribute on the specified element. Returns undefined.

嘗試在一個單獨的聲明,呼籲setAttribute

<script> 
    var divEl = document.createElement("div"); 
    document.body.appendChild(divEl); 
    var ptag = document.createElement("p"); 
    ptag.setAttribute("id", "lol"); 
    divEl.appendChild(ptag); 
</script> 

JSBin:http://jsbin.com/wibeyewuqo/edit?html,output

2

由於@vlaz指出,setAttribute()不返回節點。創建後在ptag上調用它:

var divEl = document.createElement("div"); 
document.body.appendChild(divEl); 
var ptag = document.createElement("p"); 
ptag.setAttribute("id", "lol"); 
divEl.appendChild(ptag); 
相關問題