# How to insert an element to the DOM in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 11, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-insert-element

> A quick guide to learn how to create and insert an element to the DOM by using vanilla JavaScript.

In my previous articles, we looked at how to add [markup](https://attacomsian.com/blog/javascript-update-element-html-markup) as well as [plain-text](https://attacomsian.com/blog/javascript-update-element-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](https://attacomsian.com/blog/javascript-create-dom-element) a new DOM element. Let us use this method to create a new `<div>` element:

```javascript
const div = document.createElement('div')
```

The new element is a fully manipulatable [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript) node. You can [add CSS classes](https://attacomsian.com/blog/javascript-add-remove-toggle-css-classes), set ID and other attributes, add texts and markups, and so on:

```javascript
// 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:

```javascript
// 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 a **last-child** of the target node. To insert the new element inside the `<body>` tag, use the following example:

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

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

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

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