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);

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, Buy me a coffee (cost $5) .

Need help to launch a new product? I am available for contract work. Hire me to accomplish your business goals with engineering and design.