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.
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.");
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With