HomeTutorsContact
JavaScript
How to insert an element before another using JavaScript?
Gulshan Saini
June 23, 2020
1 min

In previous article we learned how to create elements dynamically in JavaScript. Method appendChild() inserts the element as child to end of selected node.

What if we want to insert the element in between or before other elements?

Node.insertBefore()

insertBefore() method inserts a node before existing node and as a child of parent node.

Syntax

Let’s see it in action starting with below markup.

We are going to insert 🍬 Candy before second list element i.e. 🍩 Doughnut (between first and second element). The updated list would move the 🍩 Doughnut to third place.

Step 1 - Select parent node

We use getElementById() and pass id of parent node i.e. menu

Step 2 - Select second element from list

We use querySelectorAll() and pass selector #menu li as argument which would return all list elements. Then we use the index [1] to select the second element.

Step 3 - Create new list element to be inserted

First, create a list element

Next, we create a text node containing text 🍬 Candy and append it to newly created list element i.e. candy

Step 4 - Insert the new list element

Finally, we can add the newly created list element right before the second element as follows

We are going to wrap Step 3 and Step 4 in function insertCookies() and call it on a button click. This will allow us to click the button on UI and insert element dynamically before second list item.

Step 5 - Call function insertCookies() on button click

In this step we are going to add a button element that will call function insertCookies() on click. We are going to place button just before the <div id="parent"> element.

Final code

HTML

JavaScript

Working Demo

When you click on button “Insert Cookie Before Doughnut” a new cookie gets inserted before second list item. If you keep clicking the button again and again, a new cookie gets inserted at second place.

Output


Tags

#dom-manipulation
Previous Article
How to Strikethrough text in HTML?

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

How to iterate through NodeList using Javascript?
July 09, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media