appendChild does not work. New to Javascript

Riette du Toit picture Riette du Toit · Mar 12, 2013 · Viewed 11.4k times · Source

I'm new to JavaScript and I currently have an assignment. One question asks us to attach a new textNode to the <p> tag. But my appendChild doesn't want to work. All my other code works fine and does what it's supposed to. Obviously I am doing something wrong.

EDIT: In my console I am receiving an error: Uncaught TypeError: Cannot call method 'appendChild' of null

<head>
<style type="text/css">
#demo {
font-family: Verdana, Geneva, sans-serif;
font-size: 14px;
font-style: italic;
background-color: #996;
height: 25px;
width: 400px;
padding: 20px;
}
</style>
</head>

<body>

<p id = "demo">Existential div asks: &quot;Why I am I here?&quot;</p>

<script>

document.title="Tag, you're it!";

var parent=document.body;
var child=document.getElementById("demo");
parent.removeChild(child);

var para=document.createElement("p");
var node=document.createTextNode("The quick brown fox jumps over the lazy dog.");
para.appendChild(node);

var element=document.getElementById("demo");
element.appendChild(para);


with(para){
color: "#FFF";
fontFamily : "Arial";
backgroundColor: "#345";
fontSize: "30px";
textAlign: "center";
width: "600px";
height: "200px";
padding: "20px";
margin: "0px auto";
};


</script>
</body>

Answer

MarcoK picture MarcoK · Mar 12, 2013

First, you remove the element, and later on, you try to add something after that. Since it's removed, it can't be found in the DOM anymore.

var child=document.getElementById("demo");
parent.removeChild(child);

var element=document.getElementById("demo"); // returns nothing, since it was removed
element.appendChild(para);

So, simply don't remove that element if you don't want to. JSFiddle demo.