2016-12-16 45 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); 
相关问题