Add a new element to the DOM using JavaScript

Last updated: September 27, 2022.

Using JavaScript, you can create a HTML element dynamically and insert it to the DOM.

In this tutorial, we cover how to do this, including how to set content and attributes for the element and options for DOM insertion.

Table of contents

Creating the element

You can create a new element in JavaScript by calling document.createElement() and passing in a valid HTML tag name:

/* Creating elements example */

This creates a new element in JavaScript only. It doesn’t yet exist as an element in the DOM.

Setting attributes

You can add an attribute to a created element using the setAttribute() method:

/* Adding HTML attributes to a new element */
const img = document.createElement('img');
img.setAttribute('id', 'example-image');
img.setAttribute('class', 'padded centered');
img.setAttribute('src', 'my-image.png');

For standard attributes like these, you can use dot notation shorthand to set attribute values:

/* Shorthand for setting HTML attributes */
const img = document.createElement('img'); = 'example-image';
img.className = 'padded centered';
img.src = 'my-image.png';

Setting content

To set content inside the new element, use innerText, textContent or innerHTML:

/* Setting content */
const img = document.createElement('div'); = 'quote';
img.textContent = "JavaScript is the popular kid of programming languages";

Inserting to the DOM

Finally, for the attribute to appear in the DOM, you need to use an insertion method. append() and appendChild() are most common, but you may also consider preprend(), insertBefore() or insertAdjacentElement().

You can nest elements inside one another before appending.

/* Inserting a container with nested image to the DOM */

// Create elements
const div = document.createElement('div');
const img = document.createElement('img');

// Set attributes
div.className = "container"; = 'feature-image';
img.src = 'my-image.png';

// Nest image in container div and insert to DOM
const content = document.getElementById('the-content');
content.insertAdjacentElement('afterend', img);

Related links