How to insert an element to the DOM in JavaScript

published: 24 Jul 2022

2 min read

How to insert an element to the DOM in JavaScript

In my previous articles, we looked at how to add markup as well as plain-text to HTML elements by using vanilla JavaScript. In this article, you'll learn to create and inject a new element to the DOM with JavaScript.

JavaScript provides the createElement() method to create a new DOM element. Let us use this method to create a new <div> element:

const div = document.createElement('div');

The new element is a fully manipulatable DOM node. You can add CSS classes, set ID and other attributes, add texts and markups, and so on:

// set attributes
div.id = 'hint';
div.className = 'course-hint';

// add markup
div.innerHTML = '<p>Learn JavaScript</p>';

Once you are ready, use the appendChild() method to append the HTML element to the DOM:

// grab target element reference
const target = document.querySelector('#intro');

// append div to target
target.appendChild(div);

The above code will insert the new element as the last-child of the target node. To insert the new element inside the <body> tag, use the following example:

// insert element to the body
document.body.appendChild(div);

Alternatively, you can use the insertBefore() method to inserts an element to the DOM, just before or after an existing node as shown below:

// insert the element before target element
target.parentNode.insertBefore(div, target);

// insert the element after target element
target.parentNode.insertBefore(div, target.nextSibling);

How to insert an element to the DOM in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming