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 = '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

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

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 me on Twitter and LinkedIn. You can also Subscribe to RSS Feed.

Last Updated: