Adding text to an existing text element in JavaScript via DOM

Solution 1:

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

You instead just need to select the paragraph itself, and then append your new text node to that:

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

paragraph.appendChild(text);
<p id="p">This is some text</p>

However instead, if you like, you can just modify the text itself (rather than adding a new node):

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

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

Solution 2:

Instead of appending element you can just do.

 document.getElementById("p").textContent += " this has just been added";

document.getElementById("p").textContent += " this has just been added";
<p id ="p">This is some text</p>

Solution 3:

What about this.

var p = document.getElementById("p")
p.innerText = p.innerText+" And this is addon."
<p id ="p">This is some text</p>

Solution 4:

The method .appendChild() is used to add a new element NOT add text to an existing element.

Example:

var p = document.createElement("p");
document.body.appendChild(p);

Reference: Mozilla Developer Network

The standard approach for this is using .innerHTML(). But if you want a alternate solution you could try using element.textContent.

Example:

document.getElementById("foo").textContent = "This is som text";

Reference: Mozilla Developer Network

How ever this is only supported in IE 9+