Skip to main content

How to Append Text or HTML to an Element in JavaScript

Dynamically adding new content to an element is a fundamental part of creating interactive web pages. You might need to add a new comment to a list, display a status message, or insert a new piece of data retrieved from an API.

This guide will teach you the modern and safe methods for appending content. You will learn the crucial difference between appending plain text (which is safe) and appending HTML (which carries security risks). We will cover the recommended methods for each, including appendChild() with text nodes, insertAdjacentText(), and insertAdjacentHTML().

Goal: Adding Content to an Element

Given an existing HTML element, we want to add new content to the end of it without overwriting its current content.

The HTML:

<div id="box">
Initial content.
</div>

Our goal is to append more text or HTML after "Initial content.".

How to Append Plain Text (Safe)

When the content you are adding is plain text (especially if it comes from user input), you must use a method that does not parse it as HTML. This is a critical security practice to prevent Cross-Site Scripting (XSS) attacks.

Method 1: appendChild() with createTextNode()

This is the classic and most robust method. It involves two steps:

  1. Create a text node from your string. A text node is a DOM element that is guaranteed to be treated as plain text.
  2. Append this new node to your target element.
const box = document.getElementById('box');

// Step 1: Create a text node from the string
const newText = document.createTextNode(' -- This is new text.');

// Step 2: Append the text node to the element
box.appendChild(newText);
note

This is the safest method for handling user-provided content.

Method 2: insertAdjacentText()

This is a more modern and often more convenient method. It inserts a text node at a position you specify relative to the element.

To append text to the end of an element, you use the beforeend position.

const box = document.getElementById('box');

// Insert the text just inside the element, after its last child
box.insertAdjacentText('beforeend', ' -- This is also new text.');

This method is also safe from XSS attacks, as the provided string is always interpreted as text.

How to Append HTML (Use with Caution)

If the string you are adding is actual HTML that you want the browser to render, you must use a method that parses the HTML.

warning

Security Warning: Never use these methods with un-sanitized user input. If a user enters <script>...</script>, it will be executed. Only use this for trusted, self-generated HTML.

The insertAdjacentHTML() Method

This is the recommended modern method for inserting HTML. It is generally more performant than manipulating innerHTML.

For example:

const box = document.getElementById('box');

const newHtml = '<span style="color: blue;"> This is new HTML.</span>';

// Insert the HTML string just inside the element, after its last child
box.insertAdjacentHTML('beforeend', newHtml);

Why You Should Avoid Using innerHTML +=

You will often see code that appends to innerHTML using the += operator. This method should be avoided.

For example, consider the problematic innerHTML += method:

// This works, but it is inefficient and can have side effects.
box.innerHTML += '<span style="color: red;"> More HTML.</span>';
note

Why this is bad:

  • Performance: It forces the browser to re-parse and re-render the entire content of the element, not just the new part. This is very slow, especially for large elements.
  • Side Effects: It can break existing event listeners on child elements, and it can cause form inputs to lose their current state.

Conclusion: Use insertAdjacentHTML() for better performance and more predictable behavior.

Practical Example: A "Log Message" Appender

This script demonstrates the safe way to append user-provided text to a log container on the page.

The HTML:

<input type="text" id="log-input" placeholder="Enter a message">
<button id="log-button">Add Log</button>
<div id="log-container"></div>

The JavaScript:

const logInput = document.getElementById('log-input');
const logButton = document.getElementById('log-button');
const logContainer = document.getElementById('log-container');

logButton.addEventListener('click', () => {
const message = logInput.value;
if (!message) return;

// Create a new <p> element for the log entry
const newLogEntry = document.createElement('p');

// Safely set its text content (this also prevents XSS)
newLogEntry.textContent = `[LOG]: ${message}`;

// Append the new <p> element to the container
logContainer.appendChild(newLogEntry);

logInput.value = ''; // Clear the input
});

Conclusion

Appending content to the DOM is a fundamental task, and choosing the right method is critical for security and performance.

  • To append plain text (especially from users), the safest methods are creating a text node with createTextNode() and appending it with appendChild(), or using insertAdjacentText().
  • To append HTML, the recommended method is insertAdjacentHTML(). Only use this with trusted HTML strings.
  • Avoid using innerHTML += due to its poor performance and potential side effects.