· 5 min read
DOM moveBefore(): move elements without losing state
moveBefore() moves DOM elements without resetting iframes, focus, animations or popovers. How it works, its rules, and how to use it with a fallback.

moveBefore() is a DOM method that moves an element to a new position without removing it from the document first. Unlike insertBefore() or appendChild(), it keeps the element's live state: iframes don't reload, focused inputs stay focused, CSS animations keep running and open popovers stay open. It works in Chrome and Edge 133+ and Firefox 144+, but not yet in Safari, so you use it with a fallback.
That sounds like a small API. It fixes a problem that has shaped how frameworks and drag-and-drop libraries work for years.
What problem does moveBefore() solve?
The DOM has never had a real "move" operation. When you call parent.insertBefore(node, ref) on a node that is already in the document, the browser removes it and then inserts it again. For most elements that is invisible. For stateful ones, the removal step resets things:
- An
<iframe>reloads its page from scratch. - A focused
<input>loses focus. - Running CSS animations and transitions restart.
- An open popover closes, and a modal
<dialog>loses its modal state. - A fullscreen element exits fullscreen.
So if you reorder a list that contains an embedded video player, or move a chat widget from a sidebar into a modal, the user sees it reset. Libraries work around this by avoiding moves altogether: they keep stateful elements in place and shuffle their siblings around them, or position things with CSS so the DOM order never changes. Those tricks work, but they make reordering code far more complicated than it should be.
How does moveBefore() work?
The signature mirrors insertBefore():
parent.moveBefore(movedNode, referenceNode);
movedNodeis the element (or text/comment node) to move.referenceNodeis the child ofparentit should land before. Passnullto move it to the end.
The second argument is required. Calling moveBefore(node) with only one argument throws a TypeError, which is different from insertBefore(), so null is the way to append.
The method exists on Element, Document and DocumentFragment. A quick example:
const input = document.querySelector('#search');
input.focus();
document.querySelector('#toolbar').moveBefore(input, null);
document.activeElement === input; // true
Do the same with appendChild() and document.activeElement is no longer the input. In Chromium, an iframe moved with moveBefore() fires no new load event, while moving it with appendChild() reloads it and fires one.
What are the rules and errors?
A real move can't cross every boundary that a remove-and-insert can. The method throws in these cases:
| Situation | Error |
|---|---|
| The node and the new parent are in different trees (one connected, one detached) | HierarchyRequestError |
| The new parent is in a different document | HierarchyRequestError |
| The node is an ancestor of the new parent | HierarchyRequestError |
| The node is not an element or character data | HierarchyRequestError |
referenceNode is not a child of the parent | NotFoundError |
| No second argument | TypeError |
The first row is the one you'll hit. moveBefore() is for rearranging nodes that are already in the page. You can't use it to insert a freshly created element, because there's no state to preserve and no shared tree. For new nodes, keep using append() or insertBefore().
MutationObserver is the API that reports DOM changes to your code. It doesn't get a new "moved" record type. A move shows up as a removal record followed by an addition record, the same shape as before, so existing observers keep working.
How do custom elements react to a move?
Normally a custom element that gets moved runs disconnectedCallback() and then connectedCallback(), since it was technically removed and re-added. Code in those callbacks often tears down and rebuilds things like event listeners or subscriptions, which is wasted work for a move.
With moveBefore(), an element can define a new lifecycle callback, connectedMoveCallback(), and it runs instead of the other two:
class LivePlayer extends HTMLElement {
connectedCallback() {
this.startStream();
}
disconnectedCallback() {
this.stopStream();
}
connectedMoveCallback() {
// Moved within the page: keep the stream running.
}
}
customElements.define('live-player', LivePlayer);
If the class doesn't define connectedMoveCallback(), the browser falls back to the old behavior and calls disconnectedCallback() followed by connectedCallback(). Existing components stay correct; they just don't get the benefit until they opt in. If you're building components that get rearranged often, it's worth adding alongside scoped custom element registries as part of making them good citizens in larger apps.
How do you use moveBefore() today?
Safari doesn't support it yet, so treat it as a progressive enhancement. Detect it once and fall back to insertBefore():
function moveNode(parent, node, ref = null) {
if ('moveBefore' in Element.prototype && node.isConnected && parent.isConnected) {
parent.moveBefore(node, ref);
} else {
parent.insertBefore(node, ref);
}
}
The isConnected checks keep the helper safe for detached nodes, which moveBefore() would reject. In browsers without support, users get today's behavior: iframes reload and focus is lost. Nothing breaks that wasn't already broken.
Good places to use it:
- Drag-and-drop reordering of cards that contain iframes, videos or inputs.
- Responsive layouts that move a widget between a sidebar and a drawer.
- Popover and dialog content that needs to change position while open. If you open dialogs declaratively with HTML invoker commands, a move no longer closes them.
- Framework reconcilers that reorder keyed lists. This is where most of the impact will come from, since a framework can adopt it once and every app benefits.
Support at a glance:
| Browser | Support |
|---|---|
| Chrome / Edge | 133+ |
| Firefox | 144+ |
| Safari (macOS and iOS) | Not yet |
Key takeaways
moveBefore()moves a node without the remove-and-insert step, so iframes, focus, animations, popovers and fullscreen survive.- Both nodes must already be in the same document tree; it can't insert new elements.
- The second argument is required; pass
nullto append. - Custom elements can add
connectedMoveCallback()to skip teardown on moves. - Safari lacks support, so wrap it in a feature check with an
insertBefore()fallback.
FAQ
Is moveBefore() a replacement for insertBefore()?
No. Use it to rearrange nodes already in the page. For inserting new or detached nodes, insertBefore() and append() are still the right tools.
Does moveBefore() keep a video playing?
A plain <video> or <audio> element moved in one synchronous step generally keeps playing even with insertBefore(), so it doesn't depend on it. Embedded players inside iframes, like most video embeds, do need moveBefore(), because the iframe would otherwise reload.
Can I polyfill moveBefore()?
Not really. Preserving iframe and focus state needs browser support. A fallback to insertBefore() keeps your code working but with the old resetting behavior.