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>
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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With