JavaScript Element before() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline
Instance method

What You’ll Learn

Element.before() is an instance method from the ChildNode API. It inserts nodes or strings in the parent’s child list, just before the element you call it on. Learn multi-argument inserts, text coercion, how it compares to after(), and five try-it labs.

01

Kind

Instance method

02

Inserts

Before this element

03

Args

Nodes or strings

04

Returns

undefined

05

Throws

HierarchyRequestError

06

Status

Baseline widely

Introduction

Older DOM code often used parent.insertBefore(newNode, ref) to place something before a sibling. before() makes that intent clear: call it on the element that should come second, and pass what should appear ahead of it.

You can pass elements, other nodes, or plain strings. Strings become Text nodes automatically—handy for labels and spacing without creating nodes by hand.

💡
Beginner tip

before() inserts into the parent of the element you call it on. The element itself is the landmark; new content becomes its previous sibling(s). Compare with after() for inserting after the element.

This page is part of JavaScript Element. Related DOM helpers include insertBefore() and after().

Understanding the before() Method

Calling el.before(...nodes) does not add children inside el. It updates el’s parent so the new nodes sit immediately before el among siblings.

  • It is an instance method on Element (ChildNode mixin).
  • Arguments can be Node objects or strings (as Text).
  • Multiple arguments insert in the order you pass them.
  • Existing nodes in the document are moved, not cloned.
  • Return value is undefined—inspect the DOM to confirm.

📝 Syntax

General forms of Element.before (MDN):

JavaScript
before(param1)
before(param1, param2)
before(param1, param2, /* …, */ paramN)

Parameters

  • param1, …, paramN — a set of Node objects or strings to insert. Strings are inserted as equivalent Text nodes.

Return value

None (undefined).

Exceptions

  • HierarchyRequestError DOMException — thrown when the node cannot be inserted at the specified point in the hierarchy (MDN).

Common patterns

JavaScript
const p = document.querySelector("p");
const span = document.createElement("span");

p.before(span);                 // insert one element
p.before("Text");               // insert a Text node
p.before(span, "Text");         // element, then text
p.before(" · ", span, " · ");  // several siblings in order

⚡ Quick Reference

GoalCode
Insert element before elel.before(newEl)
Insert text before elel.before("Hello")
Insert several itemsel.before(a, b, "c")
Classic equivalentparent.insertBefore(node, el)
Return valueundefined
MDN statusBaseline Widely available (since April 2018)

🔍 At a Glance

Four facts to remember about Element.before().

Returns
undefined

Updates the DOM in place

Baseline
widely

Since April 2018

Where
parent list

Previous sibling(s) of el

Strings
→ Text

Auto Text nodes

📋 before() vs after() vs insertBefore()

el.before(...)el.after(...)parent.insertBefore(n, ref)
Called onThe sibling landmarkThe sibling landmarkThe parent
PositionImmediately before elImmediately after elBefore ref (or end if null)
StringsYes (as Text)Yes (as Text)No — need a Node
Return valueundefinedundefinedInserted node
Best forClear “insert before me”Clear “insert after me”Precise parent + reference

Examples Gallery

Examples follow MDN Element.before() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Insert an element, text, or both—matching MDN’s core demos.

Example 1 — Inserting an Element (MDN)

Place a new <span> immediately before a <p>.

JavaScript
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.before(span);

console.log(container.outerHTML);
// "<div><span></span><p></p></div>"
Try It Yourself

How It Works

span becomes the sibling immediately before p under container. You never call a method on the parent for this case.

Example 2 — Inserting Text (MDN)

Pass a string; the browser creates a Text node for you.

JavaScript
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);

p.before("Text");

console.log(container.outerHTML);
// "<div>Text<p></p></div>"
Try It Yourself

How It Works

No document.createTextNode needed. The string is inserted as a Text node before p.

📈 Practical Patterns

Combine args, insert several siblings, and move existing nodes.

Example 3 — Element and Text Together (MDN)

Pass an element and a string in one call—order is preserved.

JavaScript
let container = document.createElement("div");
let p = document.createElement("p");
container.appendChild(p);
let span = document.createElement("span");

p.before(span, "Text");

console.log(container.outerHTML);
// "<div><span></span>Text<p></p></div>"
Try It Yourself

How It Works

First span, then the text “Text”—both appear before p in that order.

Example 4 — Several Siblings in One Call

Build a small trail of nodes before a list item or heading.

JavaScript
const item = document.getElementById("item");
const badge = document.createElement("strong");
badge.textContent = "NEW";
const note = document.createElement("em");
note.textContent = "sale";

item.before(badge, " — ", note);

console.log(item.parentElement.innerHTML);
// <strong>NEW</strong> — <em>sale</em><li id="item">Shoes</li>
Try It Yourself

How It Works

One call inserts three nodes before item: a strong badge, a separator Text node, and an emphasis element—in that order.

Example 5 — Moving an Existing Node

If the node is already in the document, before() relocates it.

JavaScript
const list = document.getElementById("list");
const a = document.getElementById("a");
const b = document.getElementById("b");

b.before(a);

console.log([...list.children].map((el) => el.id).join(", "));
// "a, b"  (a moved to sit before b)
Try It Yourself

How It Works

Like appendChild / insertBefore, a node cannot live in two places. Use cloneNode(true) if you need a copy instead of a move.

🚀 Common Use Cases

  • Inserting a badge, icon, or label right before a title or list item.
  • Adding helper text or separators without wrapping extra containers.
  • Reordering siblings by moving an existing node ahead of another.
  • Replacing the classic parent.insertBefore(newNode, ref) pattern with clearer code.
  • Building small UI trails (element + text + element) in one call.
  • Teaching sibling insertion vs appending children inside an element.

🧠 How before() Inserts Siblings

1

Start from an element with a parent

You call el.before(...) on a node that already has a parent.

Landmark
2

Normalize arguments

Strings become Text nodes; existing nodes may detach from their old place.

Prepare
3

Insert into the parent list

New nodes sit immediately before el, in argument order.

Insert
4

DOM updated; return undefined

Check outerHTML or siblings—there is no return payload.

📝 Notes

  • Not Deprecated, Experimental, or Non-standard on MDN (Baseline Widely available since April 2018).
  • before() inserts siblings, not children of the element.
  • Return value is always undefined.
  • Invalid hierarchy can raise HierarchyRequestError.
  • Same ChildNode family: after(), append(), prepend(), replaceWith().
  • Related: after(), insertBefore(), children, JavaScript hub.

Browser Support

Element.before() is Baseline Widely available (MDN: across browsers since April 2018). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Element.before()

Safe for production. Insert nodes or text before an element with clear, modern DOM APIs.

Baseline Widely available
Google Chrome Supported · Desktop & Mobile
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Supported · Desktop & Mobile
Yes
Apple Safari Supported · macOS & iOS
Yes
Opera Supported · Modern versions
Yes
Internet Explorer Not supported · Use insertBefore polyfill pattern
No
before() Excellent

Bottom line: Prefer before() when you think “put this before that element.” Use insertBefore when you already work from the parent and a reference child. Strings become Text nodes automatically.

Conclusion

Element.before() is the modern way to insert siblings before an element—nodes, text, or several at once. It returns undefined and updates the parent’s child list in place.

Continue with after(), insertBefore(), children, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Call before() on the landmark sibling
  • Pass strings when you need Text nodes quickly
  • Pass multiple args to keep insert order clear
  • Expect moves when reusing an existing node
  • Verify with outerHTML or sibling properties

❌ Don’t

  • Expect a returned node (it is undefined)
  • Confuse sibling insert with appending inside the element
  • Assume IE supports before() without a fallback
  • Forget that invalid trees can throw HierarchyRequestError
  • Clone by accident—moves remove the old location

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.before()

Insert siblings before an element—nodes or text, one call.

5
Core concepts
📄 02

Where

before this el

Sibling
✍️ 03

Strings

become Text

Coerce
04

Baseline

widely available

Status
05

Existing

moves

DOM

❓ Frequently Asked Questions

It inserts one or more Node objects or strings into the children of this element’s parent, immediately before this element. Strings become Text nodes.
No. MDN marks Element.before() as Baseline Widely available (across browsers since April 2018). It is not Deprecated, Experimental, or Non-standard.
Nothing useful — the return value is undefined. The DOM is updated in place; check parent.outerHTML or previousSibling if you need to verify the result.
Yes. before(node1, node2, …) inserts all arguments in order, right before the element you call it on.
before() inserts siblings immediately before the element you call it on. after() inserts immediately after. Both are ChildNode helpers; insertBefore() is the classic parent-based API.
If the element is not in a parent’s child list, before() has nowhere to insert. Invalid hierarchy cases can throw a HierarchyRequestError DOMException.
Did you know?

before() comes from the ChildNode mixin—the same family as after(), remove(), and replaceWith(). That is why you call it on the sibling you care about, not on the parent container.

More Element Topics

Browse Element methods and properties to keep building your DOM skills.

after() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful