Safe Alternatives to innerHTML

A safer alternative is to use the DOM manipulation methods provided by JavaScript. Here are some alternatives to innerHTML:

1. createElement and appendChild

Create a new HTML element using document.createElement and set its content. Append the new element to an existing element using appendChild.

// Create a new element
const newElement = document.createElement("div");

// Set its content
newElement.textContent = "Your content here";

// Append it to an existing element
document.getElementById("targetElement").appendChild(newElement);

2. innerText or textContent

Set the text content of an element using either innerText or textContent properties, providing a safer way to update text without the risk of executing scripts.

// Set the text content of an element
document.getElementById("targetElement").innerText = "Your content here";

// or
document.getElementById("targetElement").textContent = "Your content here";

3. createTextNode and appendChild

Create a text node using document.createTextNode and append it to an existing element using appendChild. This is useful for adding plain text content to an element.

// Create a text node
const textNode = document.createTextNode("Your content here");

// Append it to an existing element
document.getElementById("targetElement").appendChild(textNode);

4. insertAdjacentHTML

Insert HTML at a specified position within an element using insertAdjacentHTML. This method allows you to place HTML content relative to the existing content in the target element.

// Insert HTML at a specified position
document
  .getElementById("targetElement")
  .insertAdjacentHTML("beforeend", "Your content here");

5. DocumentFragment

Use document.createDocumentFragment to create an off-document container. Append child elements to the fragment, and then append the entire fragment to an existing element. This reduces the number of DOM manipulations, improving performance.

// Create a document fragment
const fragment = document.createDocumentFragment();

// Create elements and append them to the fragment
const divElement = document.createElement("div");
divElement.textContent = "Your content here";
fragment.appendChild(divElement);

// Append the fragment to an existing element
document.getElementById("targetElement").appendChild(fragment);

Get my free, weekly JavaScript tutorials

Want to improve your JavaScript fluency?

Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.

Join today, and level up your JavaScript every Sunday!

Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.

- Remi Egwuda