Search code examples
javascriptappendchildtextnode

appendChild does not work. New to Javascript


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>

Solution

  • Your logic is wrong.

    You remove the element called demo in these lines

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

    You then try to append a child node to the node you've just removed here:

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

    You can't append an element to an element that no longer exists. If you delete the removeChild line, then everything should work.

    Also, your with block is wrong, you need to change it to:

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

    After that, everything should be good.