Inserting Elements with Vanilla JavaScript

Insert new HTML elements into the DOM or move existing HTML elements to anywhere in the document using vanilla JavaScript

Mehdi Namvar
6 min readFeb 23, 2022

--

Most developers underestimate the power of vanilla JavaScript that’s why I started writing this series of articles on vanilla JS. Hopefully, it will help avoid using unnecessary external libraries.

I’m gonna begin with creating new HTML elements and inserting them into the document. It’s crucial to know how you can create new elements and insert them exactly where you want them.

Creating New HTML Elements

To create and insert a new element to the page, first, you create the element and then attach it to the document. To create an element, you will use the document method createElement:

var h1 = document.createElement('h1')

When you create a new element, it is empty in the first place, so the h1 element is something like this:

<h1></h1>

One thing you should know is that this h1 element is still NOT inserted into the page. After creating the element, you will need to attach it somewhere in the document tree. You can easily append it to the body, for instance:

--

--