JavaScript Element moveBefore() Method

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

What You’ll Learn

Element.moveBefore() is an instance method that moves a node inside the caller as a direct child, before a reference node. Unlike insertBefore(), it preserves focus, animations, popover state, and more (MDN). Learn the MDN toggle demo, null reference append, constraints, feature detection, and five try-it labs aligned with MDN.

01

Kind

Instance method

02

Moves

Element or text

03

Args

movedNode + ref

04

Returns

undefined

05

Preserves

focus, state

06

Status

Limited availability

Introduction

When you rearrange UI with insertBefore() or prepend(), the browser removes the node and inserts it again. That can reset focus, close popovers, interrupt CSS transitions, and disturb other element state.

moveBefore(movedNode, referenceNode) moves a node to a new position without that remove-and-reinsert cycle (MDN). The node keeps its interactive and visual state—a big win for draggable panels, live video embeds, and modals.

💡
Beginner tip

Pass null as referenceNode to append movedNode at the end of the parent’s children (MDN).

This page is part of JavaScript Element. Compare with before() and append() for other DOM insertion patterns.

Understanding the moveBefore() Method

Calling parent.moveBefore(movedNode, referenceNode) relocates movedNode inside parent, immediately before referenceNode.

  • It is an instance method on Element (MDN).
  • movedNode must be an Element or CharacterData node.
  • referenceNode must be a child of the caller, or null to append.
  • Returns undefined (MDN).
  • Preserves animation, focus, popover, modal, and loading state (MDN).
  • Only works within the same document; connected/disconnected mismatches throw (MDN).
  • MutationObserver records a removed node and an added node for the move (MDN).

📝 Syntax

General form of Element.moveBefore (MDN):

JavaScript
moveBefore(movedNode, referenceNode)

Parameters

NameTypeDescription
movedNodeNodeThe node to move. Must be an Element or CharacterData node (MDN).
referenceNodeNode or nullThe child before which movedNode is placed, or null to append at the end of the parent’s children (MDN).

Return value

TypeDescription
undefinedNone (undefined) — the method updates the DOM in place (MDN).

Exceptions

  • HierarchyRequestError — invalid moves such as cross-document, disconnected nodes, moving an ancestor into a descendant, invalid referenceNode, missing second argument, or wrong node type (MDN).

Common patterns

JavaScript
// MDN toggle: move before section1 or section2
if (mover.nextElementSibling === section1) {
  wrapper.moveBefore(mover, section2);
} else {
  wrapper.moveBefore(mover, section1);
}

// Append to end of a container
section2.moveBefore(mover, null);

// Feature-detect with insertBefore fallback
function moveNode(parent, node, ref) {
  if (typeof parent.moveBefore === "function") {
    parent.moveBefore(node, ref);
  } else {
    parent.insertBefore(node, ref);
  }
}

⚡ Quick Reference

GoalCode
Move before a childparent.moveBefore(node, ref)
Append at endparent.moveBefore(node, null)
MDN toggle patternwrapper.moveBefore(mover, section2)
Feature detecttypeof el.moveBefore === "function"
Return valueundefined
MDN statusLimited availability (not Baseline)

🔍 At a Glance

Four facts to remember about Element.moveBefore().

Returns
void

undefined

Status
limited

Not Baseline

Preserves
state

focus, popovers

null ref
append

End of children

📋 moveBefore() vs insertBefore() vs prepend()

moveBefore()insertBefore()prepend()
MechanismMove in placeRemove + reinsertRemove + reinsert
Preserves stateYes (MDN)Often resetsOften resets
Return valueundefinedMoved nodeundefined
Browser supportLimitedUniversalBaseline
Best forStateful UI movesFallback / legacySimple prepend

Examples Gallery

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

📚 Getting Started

MDN’s basic toggle—move a box between two sections.

Example 1 — MDN Toggle Between Sections

Click a button to move #mover before #section1 or #section2.

JavaScript
const wrapper = document.getElementById("wrapper");
const section1 = document.getElementById("section1");
const section2 = document.getElementById("section2");
const mover = document.getElementById("mover");

moveBtn.addEventListener("click", () => {
  if (mover.nextElementSibling === section1) {
    wrapper.moveBefore(mover, section2);
  } else {
    wrapper.moveBefore(mover, section1);
  }
});
Try It Yourself

How It Works

MDN checks nextElementSibling to decide which section should receive the mover next. Each click calls moveBefore() on the wrapper.

Example 2 — Append with null Reference

Move a node to the end of a container by passing null (MDN).

JavaScript
const section1 = document.getElementById("section1");
const section2 = document.getElementById("section2");
const mover = document.getElementById("mover");

if (mover.parentElement === section1) {
  section2.moveBefore(mover, null); // append inside section2
} else {
  section1.moveBefore(mover, null); // append inside section1
}
Try It Yourself

How It Works

When referenceNode is null, MDN says movedNode is inserted at the end of the parent’s child list.

📈 Practical Patterns

State preservation, fallbacks, and feature detection.

Example 3 — Focus Preserved After Move

Move an input between containers; focus stays on the field with moveBefore().

JavaScript
const field = document.getElementById("field");
const boxA = document.getElementById("boxA");
const boxB = document.getElementById("boxB");

field.focus();
const hadFocus = document.activeElement === field;

boxB.moveBefore(field, null);

console.log(hadFocus && document.activeElement === field);
// true — focus preserved (MDN)
Try It Yourself

How It Works

MDN lists interactivity states such as :focus among preserved state. insertBefore() would typically blur the field after a remove/reinsert.

Example 4 — Fallback to insertBefore()

Use moveBefore() when available; otherwise fall back safely.

JavaScript
function moveNode(parent, node, ref) {
  if (typeof parent.moveBefore === "function") {
    parent.moveBefore(node, ref);
  } else {
    parent.insertBefore(node, ref);
  }
}

moveNode(section2, mover, null);
console.log("moved with fallback support");
Try It Yourself

How It Works

MDN recommends insertBefore() when constraints block moveBefore(), or when the API is missing. This pattern keeps older browsers working.

Example 5 — Feature Detection

Check support before calling the method in production UI.

JavaScript
const parent = document.getElementById("wrapper");
const supported = typeof parent.moveBefore === "function";

console.log(supported ? "moveBefore available" : "use insertBefore fallback");

if (supported) {
  parent.moveBefore(mover, section1);
}
Try It Yourself

How It Works

Because MDN marks limited availability, always detect before relying on moveBefore() in cross-browser apps.

🚀 Common Use Cases

  • Dragging panels between columns without losing focus (MDN).
  • Moving video or iframe embeds while preserving playback state (MDN demo).
  • Reordering list items in a sortable UI with animations intact.
  • Keeping popovers and modals open during DOM repositioning.
  • Custom elements moved with connectedMoveCallback() instead of disconnect/connect (MDN).
  • Progressive enhancement with insertBefore() fallback.

🧠 How moveBefore() Relocates a Node

1

Choose parent + nodes

parent.moveBefore(movedNode, referenceNode) (MDN).

Args
2

Validate constraints

Same document, valid reference child, correct node types—or throw HierarchyRequestError.

Check
3

Move in place

Node is repositioned without remove/reinsert—state preserved (MDN).

Move
4

Done — returns undefined

movedNode now sits before referenceNode (or at end if null).

📝 Notes

  • Limited availability on MDN — not Baseline; feature-detect before use.
  • Returns undefined (MDN).
  • referenceNode === null appends at the end of children (MDN).
  • Preserves focus, animations, popovers, modals, and loading state (MDN).
  • Same-document only; connected/disconnected mismatches throw (MDN).
  • Related: before(), append(), matches(), JavaScript hub.

Browser Support

Element.moveBefore() has limited availability on MDN (not Baseline). Logos use the shared browser-image-sprite.png sprite from this project.

Experimental · Not Baseline

Element.moveBefore()

Move nodes while preserving focus and UI state — limited cross-browser support.

Limited Not Baseline
Google Chrome Supported · Recent versions
Yes
Microsoft Edge Supported · Chromium
Yes
Mozilla Firefox Check current MDN table
Partial
Apple Safari Check current MDN table
Partial
Opera Chromium-based versions
Yes
Internet Explorer Not supported
No
moveBefore() Growing

Bottom line: Feature-detect moveBefore() and fall back to insertBefore() where needed. Use it when preserving element state during DOM moves matters.

Conclusion

Element.moveBefore() relocates a node inside a parent while preserving interactive and visual state—something insertBefore() often disrupts. Pass null to append, feature-detect for limited browsers, and fall back when needed.

Continue with matches(), append(), shadowRoot, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Feature-detect: typeof parent.moveBefore === "function"
  • Fall back to insertBefore() when unsupported (MDN)
  • Use null reference to append at end (MDN)
  • Prefer for stateful moves: focus, popovers, animations
  • Wrap risky moves in try/catch for HierarchyRequestError

❌ Don’t

  • Assume Baseline support—check MDN compatibility first
  • Move nodes across different documents
  • Move disconnected nodes into connected parents (or vice versa)
  • Move an ancestor into its own descendant
  • Omit the second referenceNode argument (throws per MDN)

Key Takeaways

Knowledge Unlocked

Five things to remember about Element.moveBefore()

Move nodes without losing UI state.

5
Core concepts
📄 02

Preserves

focus

State
✍️ 03

null ref

append

MDN
04

Status

limited

Detect
05

vs

insertBefore

Fallback

❓ Frequently Asked Questions

It moves a given Node inside the invoking element as a direct child, before a reference node (MDN). Unlike insertBefore(), it does not remove and reinsert the node, so element state is preserved.
MDN marks Element.moveBefore() as limited availability (not Baseline). It is a newer DOM API with limited cross-browser support. Feature-detect before using it in production.
Nothing useful — the return value is undefined (MDN).
If referenceNode is null, movedNode is inserted at the end of the invoking element's child nodes (MDN).
insertBefore() removes and reinserts the node, which can reset focus, animations, and popover state. moveBefore() moves the node while preserving that state (MDN).
HierarchyRequestError for invalid moves (wrong document, disconnected nodes, ancestor moves, invalid referenceNode, missing second argument, or non-Element/CharacterData movedNode) per MDN.
Did you know?

MDN’s YouTube embed demo shows a key difference: moving with insertBefore() or prepend() resets playback, but moveBefore() keeps the video playing.

More Element Topics

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

prepend() →

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