JavaScript before()

Summary: in this tutorial, you’ll learn how to use the JavaScript before() method to insert a node before an element.

Introduction to the JavaScript before() method

The element.before() method allows you to insert one or more nodes before the element. The following shows the syntax of the before() method:

Element.before(node)Code language: JavaScript (javascript)

In this syntax, the before() method inserts the node before the Element in the DOM tree.

For example, suppose you have a <p> element and you want to insert a <h1> element before it, you can use the before() method like this:

p.before(h1)Code language: JavaScript (javascript)

To insert multiple nodes before an element, you pass the nodes to the before() method as follows:

Element.before(node1, node2, ... nodeN)Code language: JavaScript (javascript)

Also, the before() method accepts one or more strings rather than nodes. In this case, the before() method treats the strings as Text nodes:

Element.before(str1, str2, ... strN)Code language: JavaScript (javascript)

The before() method returns undefined. If a node cannot be inserted, the before() method throws a HierarchyRequestError exception.

JavaScript before() examples

Let’s take some examples of using the JavaScript before() method.

1) Using JavaScript before() to insert a node before an element

The following example uses the before() method to insert a <h1> before a paragraph:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JavaScript DOM - before()</title>
    </head>

    <body>

        <p>This is JavaScript DOM before() method demo.</p>

        <script>
            const p = document.querySelector('p');

            // create a new h1 element
            const h1 = document.createElement('h1');
            h1.innerText = 'JavaScript DOM - before()';

            // insert the h1 before the paragraph
            p.before(h1);
        </script>
    </body>

</html>Code language: JavaScript (javascript)

How it works.

First, get the <p> element using the querySelector() method:

const p = document.querySelector('p');Code language: JavaScript (javascript)

Second, create a new heading element and set its innerText:

const h1 = document.createElement('h1');
h1.innerText = 'JavaScript DOM - before()';
Code language: JavaScript (javascript)

Third, insert the <h1> element before the paragraph element:

p.before(h1);Code language: JavaScript (javascript)

2) Using JavaScript before() to insert multiple nodes before an element

The following example uses the before() method to insert multiple nodes before an element:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JavaScript DOM - before()</title>
    </head>

    <body>
        <ul>
            <li>Angular</li>
            <li>Vue</li>
        </ul>
        <script>
            const list = document.querySelector('ul');

            const libs = ['React', 'Meteor', 'Polymer'];
            const items = libs.map((lib) => {
                const item = document.createElement('li');
                item.innerText = lib;
                return item;
            });

            list.firstChild.before(...items);

        </script>
    </body>

</html>Code language: JavaScript (javascript)

How it works:

First, select the ul element using the querySelector() method:

 const list = document.querySelector('ul');Code language: JavaScript (javascript)

Second, define an array of strings. In practice, you may get it from an API call.

 const libs = ['React', 'Meteor', 'Polymer'];Code language: JavaScript (javascript)

Third, transform the array of strings into an array of li elements using the map() method:

const items = libs.map((lib) => {
  const item = document.createElement('li');
  item.innerText = lib;
  return item;
});Code language: JavaScript (javascript)

Finally, insert the list item elements before the first child of the ul element:

list.firstChild.before(...items);Code language: JavaScript (javascript)

Note that the ...items uses the spread operator to spread out the element of the items array.

The <ul> element will look like the following:

<ul>
    <li>React</li>
    <li>Meteor</li>
    <li>Polymer</li>
    <li>Angular</li>
    <li>Vue</li>
</ul>Code language: HTML, XML (xml)

The first three items (React, Meteor, and Polymer) were inserted before the item Angular, which was the first child of the <ul> element.

3) Using JavaScript before() to insert strings

When you use strings in the before() method, the before() method will treat them as Text nodes. For example:

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>JavaScript DOM - before()</title>
        <style>
            button {
                padding: 0.75em 1em;
                background-color: #F7DF1E;
                color: #000;
                cursor: pointer;
                border-radius: 50vw;
            }
        </style>
    </head>

    <body>
        <button>Donate Here</button>
        <script>
            const button = document.querySelector('button');
            button.firstChild.before('🧡 ');

        </script>
    </body>

</html>Code language: JavaScript (javascript)

Summary

  • Use the element.before() method to insert one or more nodes before the element.
Was this tutorial helpful ?