Favorites

DOM Element.before() Method

☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee
Element.before()
DOM Element MethodThis method is supported by all modern browsers.
Updated 28th November 2026

The before() method inserts nodes or text just before an element, as siblings. The after() method inserts them just after.

Description

The before() method inserts nodes or strings into the element's parent just before the element, and after() inserts them just after it. They're the sibling equivalents of prepend() and append().

Both methods accept several arguments, mixing nodes and strings, and insert them in the order given. If the element has no parent, they do nothing.

They're more convenient than insertBefore() because they're called on the reference element itself, and after() fills the gap left by the lack of an insertAfter() method. Strings are added as text, so they're safe from HTML injection.

Syntax

element.before(param1, param2, ...)
element.after(param1, param2, ...)

Parameters

  • param1, param2, ...Nodes or strings to insert.

Return Value

None (undefined).

Example

<p id="p">Paragraph</p>
const p = document.getElementById('p');
const h = document.createElement('h3');
h.textContent = 'Heading';
p.before(h);
p.after('Text after the paragraph');
console.log(document.body.innerHTML.trim());

Browser Support

The following information will show you the current browser support for the Element.before() method. Hover over a browser icon to see the version that first introduced support for this method.

This method is supported by all modern browsers.

Desktop

Chrome
Edge
Firefox
Opera
Safari

Tablets & Mobile

Chrome Android
Firefox Android
Opera Android
Safari iOS
Samsung Internet
Android WebView
-
Supported Unknown Not supported
☕
Enjoying this site?

Help keep it running with a small coffee donation. Every bit of support is appreciated!

Buy us a coffee