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 using 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 a 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 insert 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.