Borislav Hadzhiev
Last updated: Jan 4, 2022
Check out my new book
To append text to an element:
document.createTextNode()
method to create a text node.appendChild()
method to append the text node to the element.appendChild
method will add the text node to the end of the element's
list of children.Here is the HTML for the examples in this article.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"> Hello <span style="background-color: salmon">world</span> </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
// ✅ Append text to element const box = document.getElementById('box'); const text = document.createTextNode('!!!'); box.appendChild(text); // ✅ (Alternative) Append text using insertAdjacentText box.insertAdjacentText('beforeend', '???'); // ✅ Append HTML to element box.insertAdjacentHTML( 'beforeend', '<span style="background-color: yellow"> Additional html</span>', );
We selected the element we want to append text to using the
document.getElementById()
method.
The next step is to create a text node using the document.createTextNode method.
The method takes a string and creates a text node from it.
The last step is to use the Node.appendChild method to append the text node to the end of the element's children.
If you need to append HTML
to an element and not just text, you can use this
approach instead:
const box = document.getElementById('box'); box.insertAdjacentHTML( 'beforeend', '<span style="background-color: yellow"> Additional html</span>', );
The insertAdjacentHTML() method takes the following 2 parameters:
position
- the position relative to the element of where the HTML should be
inserted. Can be one of the following:
beforebegin
- before the element itself.afterbegin
- just inside the element, before its first child.beforeend
- just inside the element, after its last child.afterend
- after the element itself.text
- the string to be parsed as HTML and inserted into the DOM.
It should be noted that you shouldn't append HTML that is from user generated input without escaping it.
There is also an insertAdjacentText method you can use.
Use the insertAdjacentText()
method to append text to an element, e.g.
el.insertAdjacentText('beforeend', 'my text')
. The method takes a position and
a string as parameters and inserts a new text node at the provided position
relative to the element it was called on.
const box = document.getElementById('box'); box.insertAdjacentText('beforeend', ' additional text ');
The first parameter of the insertAdjacentText
method is the same as
insertAdjacentHTML
- the position at which we want to insert the text node.
insertAdjacentText
method as it is more concise and direct.