Add a new element to the DOM using JavaScript

Reading Time: 2 minutes 🕑

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 */
document.createElement('p');
document.createElement('article');
document.createElement('img');

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');
img.id = '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');
img.id = '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";
img.id = 'feature-image';
img.src = 'my-image.png';

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

Related links