I'm trying to figure out how to add text to a tag p or h1 that already has a text node

For example.

var t = document.getElementById("p").textContent;
var y = document.createTextNode("This just got added");

<p id="p">This is some text</p>

This code gives an error appendchild is not a function. Most of the help pages first create a tag and then append the text

How do you add text to existing text elements?

Ps i have used innerhtml before to do this but for learning purposes i want to avoid it here

Best Answer

The reason that appendChild is not a function is because you're executing it on the textContent of your p element.

Instead you can just select the paragraph itself and then append your new text to it

var paragraph = document.getElementById("p");
var text = document.createTextNode("This just got added");

<p id="p">This is some text</p>

You can change the text itself instead of adding a new node if you want

var paragraph = document.getElementById("p");

paragraph.textContent += "This just got added";
<p id="p">This is some text</p>