JavaScript’s Element.before() method inserts a set of Node or string objects before the Element.


Element.before(parameter1, parameter2, /* … , */ parameterN)


One or more Node or string objects.

Return value

The before() method does not have a return value, which means that the method implicitly returns undefined.


HierarchyRequestError DOMException

Thrown when the node cannot be inserted at the specified point in the hierarchy.


Here are some examples of using the JavaScript before() method.

Inserting an element

Suppose we would like to add a new menu item before the last item of this menu:

<ul id="menu">
 <li>Contact Me</li>

How could we manage that?

Well, we can select the last li element with the querySelector() method, create a new li element, and use the before() method to insert the new element before the last element:

let last = document.querySelector('#menu li:last-child');
let li = document.createElement('li');
li.textContent = 'About Me';

This is how our HTML looks like now:

<ul id="menu">
 <li>About Me</li>
 <li>Contact Me</li>

Inserting text

We can also use the before() method to insert text. This is how we could add some text before our menu:

let menu = document.getElementById('menu');
menu.before('Please select something from our menu.');

Now our HTML would look like this:

Please select something from our menu.
<ul id="menu">
 <li>About Me</li>
 <li>Contact Me</li>

Browser compatibility

Internet Explorer
Chrome (Android)
Firefox (Android)
Opera (Android)
Safari (iOS)
Samsung Internet
WebView (Android)
before() 54 17 49 39 10 54 49 41 10 6.0 54

See also