HomeTutorsContact

How to insert an element before another using JavaScript?

By Gulshan Saini
Published in JavaScript
June 23, 2020
1 min read

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

// node -> parent node
// existingnode -> existing child inside parent node
// newnode -> node to be inserted
node.insertBefore(newnode, existingnode)

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

<div id="parent">
  <h1>Today's menu</h1>
  <ul>
    <li>🍕Pizza</li>
    <li>🍩 Doughnut</li>
    <li>🍔 Hamburger</li>
  </ul>
</div>

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

const menu = document.getElementById('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.

// get second item from list i.e. 🍩 Doughnut
let doughnut = document.querySelectorAll('#menu li')[1]

Step 3 - Create new list element to be inserted

First, create a list element

let candy = document.createElement('li')

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

candy.appendChild(document.createTextNode('🍬 Candy'))

Step 4 - Insert the new list element

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

// insert 🍬 Candy before doughnut
menu.insertBefore(candy, doughnut)

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.

...
<button id="addItem" onclick="insertCookies()">
  Insert Cookie Before Doughnut
</button>
<div id="parent">
  ...
</div>

Final code

HTML

<h1>Today's menu</h1>
<button id="addItem" onclick="insertCookies()">
  Insert Cookie Before Doughnut
</button>
<div id="parent">
  <ul id="menu">
    <li>🍕Pizza</li>
    <li>🍩 Doughnut</li>
    <li>🍔 Hamburger</li>
  </ul>
</div>

JavaScript

// get handle of target element
const menu = document.getElementById('menu')

// get second item from list i.e. 🍩 Doughnut
let doughnut = document.querySelectorAll('#menu li')[1]

function insertCookies() {
  let candy = document.createElement('li')
  candy.appendChild(document.createTextNode('🍬 Candy'))

  // insert 🍬 Candy before doughnut
  menu.insertBefore(candy, doughnut)
}

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?

Related Posts

JavaScript
How to iterate through NodeList using Javascript?
July 09, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Angular
JavaScript
ReactJS
Typescript
Linux

Subscribe to our newsletter!

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

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media