JavaScript’s Element.before()
method inserts a set of Node
or string objects before the Element
.
Syntax
Element.before(parameter1)
Element.before(parameter1, parameter2, /* … , */ parameterN)
Parameters
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
.
Exceptions
HierarchyRequestError
DOMException
Thrown when the node cannot be inserted at the specified point in the hierarchy.
Examples
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>Home</li>
<li>Blog</li>
<li>Contact Me</li>
</ul>
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';
last.before(li);
This is how our HTML looks like now:
<ul id="menu">
<li>Home</li>
<li>Blog</li>
<li>About Me</li>
<li>Contact Me</li>
</ul>
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>Home</li>
<li>Blog</li>
<li>About Me</li>
<li>Contact Me</li>
</ul>
Browser compatibility
Chrome
|
Edge
|
Firefox
|
Internet Explorer
|
Opera
|
Safari
|
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 |