Cannot appendChild of "null"?

So I’m trying to make it so that when a user presses the “send” button, the text typed into the input “messageInput” will appear in a new

element inside the div “content”.


document.getElementById(“send”).onclick = function() {
var message = document.getElementById(“messageInput”).value;
if (message == “”) {

// nothing 

} else {
var message = document.getElementById(“messageInput”).value;
var para = document.createElement(“p”);
var node = document.createTextNode(message);
var element = document.getElementById(“content”);

I took this code from w3schools so I’m unsure why there’s an error. The error is basically “Uncaught TypeError: Cannot read property ‘appendChild’ of null”. The error occurs at the line “element.appendChild(para)”.
Alright, sorry if this was a repeat, it didn’t seem to be one when I checked, and apologies if my error is extremely obvious. Thanks in advance.

Hey @penguinlino its a little difficult to fully debug this without your html but looks like document.getElementById(“content”) is returning null, are you sure that there is an element in your html with id “content”?

1 Like

Wrap your code in a window.onload function, or move the script tag to the bottom of the page. Also make sure that an element with the id “content” exists.


You should probably put it on the bottom of <body> because head scripts can be weird at times

ah I checked again, thanks for reminding me. I got class confused with id, so apologies for the stupid mistake. but anyways thanks!

1 Like

no worries! glad you sorted it out :slight_smile:

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.