Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text to an existing text element in JavaScript via DOM

Tags:

javascript

dom

I am trying to figure how to add text to a p tag or h1 tag that already has a text node.

For example:

var t = document.getElementById("p").textContent; var y = document.createTextNode("This just got added");  t.appendChild(y);
<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 p tag and then append the text.

What is the right way to add text to an existing text element?

PS: I've used innerHTML before to do this, but for learning purposes I want to avoid it here.

like image 400
Benny Thadikaran Avatar asked Jan 20 '17 12:01

Benny Thadikaran


People also ask

How do I add text to DOM element?

To add text to the <p> element, you must create a text node first. This code creates a text node: const node = document. createTextNode("This is a new paragraph.");


2 Answers

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>
like image 185
James Monger Avatar answered Sep 25 '22 15:09

James Monger


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>
like image 23
Deep Avatar answered Sep 21 '22 15:09

Deep