Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript website error: Uncaught TypeError: Failed to execute 'appendChild' on 'Node'

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>
like image 679
Olaf lol Avatar asked Dec 21 '25 23:12

Olaf lol


2 Answers

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

like image 181
Jonathan.Brink Avatar answered Dec 24 '25 20:12

Jonathan.Brink


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);
like image 31
Fueled By Coffee Avatar answered Dec 24 '25 19:12

Fueled By Coffee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!