Append text to a Paragraph element using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jan 4, 2022

banner

Check out my new book

Append text to a Paragraph element using JavaScript #

Use the insertAdjacentText() method to append text to a paragraph element, e.g. p.insertAdjacentText('beforeend', 'my text'). The method inserts a new text node at the provided position, relative to the element it was called on.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <p id="paragraph"> One, <span style="background-color: aquamarine">Two,</span> </p> <script src="index.js"></script> </body> </html>

And here is the related JavaScript text.

index.js
const p = document.getElementById('paragraph'); // ✅ Append text to paragraph p.insertAdjacentText('beforeend', ' Three'); // ✅ Append HTML to paragraph p.insertAdjacentHTML( 'beforeend', '<span style="background-color: yellow">, Four</span>', );

We used the document.getElementById() method to select the paragraph.

The insertAdjacentText method takes the following 2 parameters:

  1. position - the position relative to the element of where the text should be inserted. Can be one of the following 4:
  • 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.
  1. data - the string from which to create a new text node to insert at the given position.

In the example, we inserted text just inside the p element, after its last child, but you can change the first parameter depending on your use case.

An alternative approach is to create a text node and append it to the p element.

index.js
const p = document.getElementById('paragraph'); const textNode = document.createTextNode(' Three'); p.appendChild(textNode);

The createTextNode method takes a string and creates a text node from it.

The method escapes HTML characters, so you don't have to worry about XSS attacks when working with user generated input.

The next step is to use the appendChild method to append the text node to the end of the element's list of children.

If you need to append HTML to the p element, use the insertAdjacentHTML method.

index.js
const p = document.getElementById('paragraph'); // ✅ Append HTML to paragraph p.insertAdjacentHTML( 'beforeend', '<span style="background-color: yellow">, Four</span>', );

The first parameter the method takes is the same as with insertAdjacentText - the position at which the HTML should be inserted.

The second parameter is an HTML string.

This method shouldn't be used with user provided input without it being escaped, as it would be a vector for XSS attacks.
Use the search field on my Home Page to filter through my more than 3,000 articles.