Reputation: 87
Hey I am trying to make a website With just JavaScript but I get this error:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'at html:12:9
Here is my html code:
<!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>
Upvotes: 3
Views: 165
Reputation: 25373
setAttribute
does not return a node, so your ptag
variable is getting set to undefined
.
From the doc:
Adds a new attribute or changes the value of an existing attribute on the specified element. Returns undefined.
Try calling setAttribute
in a separate statement:
<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
Upvotes: 3
Reputation: 2559
As @vlaz pointed out, setAttribute()
doesn't return a node. Call this on ptag after creating it:
var divEl = document.createElement("div");
document.body.appendChild(divEl);
var ptag = document.createElement("p");
ptag.setAttribute("id", "lol");
divEl.appendChild(ptag);
Upvotes: 2