Element.moveBefore(): Move DOM Nodes Without Resets

Element.moveBefore() moves a node to a new place in the same document without the remove-and-reinsert that insertBefore() and appendChild() do. The node keeps its state: an iframe does not reload, a focused input stays focused, a modal <dialog> stays modal and an open popover stays open. It ships in Chrome and Edge 133 and Firefox 144. Safari does not have it yet.

That is the whole API. The signature is the same as insertBefore(), so parent.moveBefore(node, referenceNode) puts node before referenceNode, and null as the second argument appends it.

Why does moving an iframe make it reload?

Because the DOM never had a move. Every existing way of relocating a node (insertBefore, appendChild, append, prepend, replaceWith) is specified as a removal followed by an insertion. Removal runs the element’s removing steps, and for a lot of elements those steps throw state away. An iframe’s browsing context is discarded, so it loads its document again when it is reinserted. A showing popover is hidden. A modal dialog leaves the top layer. A focused element loses focus.

We checked this rather than trusting the list. Our test page held an iframe that counts its own loads, a focused text input, a modal dialog, an open popover and two custom elements. We moved each into another container with each method, in Playwright’s Chromium 149, Firefox 151 and WebKit 26.5 builds. With insertBefore(), all three engines behaved the same way:

  • the iframe loaded a second time
  • document.activeElement was no longer the input (the typed value survived, focus did not)
  • the dialog still had its open attribute but no longer matched :modal, so it had dropped out of the top layer, taking its backdrop and the inertness of the rest of the page with it
  • the popover no longer matched :popover-open

The dialog case is the nasty one. Nothing throws, the dialog is still visible, and the rest of the page has quietly become interactive again behind it.

With moveBefore() in Chromium and Firefox, the iframe loaded once, the input kept focus, the dialog stayed modal and the popover stayed open. That matches the preserved-state list on MDN’s moveBefore page: animation and transition state, iframe loading state, :focus and :active, fullscreen, popover open state and dialog modal state. MDN also notes that <video> and <audio> play state was never on that list, because media elements already keep playing when they are removed and reinserted.

How do you use moveBefore with a fallback?

Feature-detect it, and catch the one exception that means “this move is not allowed, do a normal insert instead”.

/**
 * Move a node without resetting its state where the browser allows it.
 * Falls back to insertBefore() when moveBefore() is missing or refuses the move.
 */
export function moveNode(parent: ParentNode & Node, node: Element | CharacterData, before: Node | null = null): boolean {
  if ("moveBefore" in parent) {
    try {
      parent.moveBefore(node, before);
      return true;
    } catch (error) {
      if (!(error instanceof DOMException && error.name === "HierarchyRequestError")) throw error;
    }
  }
  parent.insertBefore(node, before);
  return false;
}

The return value says which path ran, so you can log how often the fallback fires. Any other error (a NotFoundError because before is not a child of parent, say) is rethrown, because insertBefore() would fail on the same input anyway.

On types: TypeScript 6.0’s lib.dom.d.ts declares moveBefore on the ParentNode interface, which Element, Document and DocumentFragment all extend. TypeScript 5.9 does not declare it, so the in check narrows parent.moveBefore to unknown and the build fails with TS18046: 'parent.moveBefore' is of type 'unknown'. Until you upgrade, a global declaration fixes it:

// movebefore.d.ts: only needed on TypeScript 5.9 and earlier
declare global {
  interface ParentNode {
    moveBefore(node: Node, child: Node | null): void;
  }
}

export {};

The helper type-checks with --strict on TypeScript 5.9.3 with that file, and on 6.0.3 and 7.0.2 without it. Delete the file when you move to 6.0.

When does moveBefore throw HierarchyRequestError?

The DOM Standard’s move algorithm starts by checking that the new parent and the node share a shadow-including root. In practice that rules out three things:

  1. Moving a detached node into the document, or a connected node into a detached tree. A freshly created element has never been connected, so document.body.moveBefore(document.createElement("span"), null) throws in Chromium and Firefox, and the helper falls back to inserting it.
  2. Moving between documents, which includes moving a node from the main page into an iframe’s document.
  3. Moving something that is not an Element or CharacterData node, such as a DocumentFragment. A fragment is never connected to the document anyway, so keep using append() for those.

It also throws HierarchyRequestError if the node is an ancestor of the new parent, exactly as insertBefore() does. Two smaller traps: the second argument is required (leave it out and you get a TypeError, so pass null to append), and a reference node that is not a child of the parent throws NotFoundError.

Do custom elements get disconnectedCallback on a move?

By default, yes. The HTML Standard says that when a custom element is moved and its class has no connectedMoveCallback, the browser runs disconnectedCallback and then connectedCallback instead. Our test confirmed it: an element without the hook logged a disconnect and a connect on moveBefore(), exactly as it did on insertBefore().

To opt out, define connectedMoveCallback. The spec is explicit that its existence, even with an empty body, replaces the disconnect/connect pair.

class LiveClock extends HTMLElement {
  connectedCallback() {
    this.timer = setInterval(() => {
      this.textContent = new Date().toLocaleTimeString("en-GB");
    }, 1000);
  }

  disconnectedCallback() {
    clearInterval(this.timer);
  }

  connectedMoveCallback() {
    // Present, even if empty, so moveBefore() skips the
    // disconnectedCallback/connectedCallback pair.
  }
}

customElements.define("live-clock", LiveClock);

Moved with moveBefore() in Chromium and Firefox, this element kept the same interval handle and carried on ticking. If your component reads anything from its ancestors (a theme from the nearest wrapper, a form owner), connectedMoveCallback is where to recompute it, because the parent has changed even though the element was never disconnected. This matters for libraries built on Shadow DOM and custom elements: an element that tears down its own state in disconnectedCallback will do it on every move unless it adds the hook.

What else still sees a remove and an insert?

MutationObserver. The spec queues one record on the old parent with the node in removedNodes and one on the new parent with it in addedNodes, and that is what we saw in both engines. Code that watches for removals to clean up (analytics, lazy-load observers, editor plugins) will still fire on a moveBefore(). If that cleanup is destructive, check node.isConnected inside the callback before acting, because a moved node is still connected when the records arrive.

Frameworks are the other gap. React DOM 19.3.1, the current release on npm on 20 November 2026, has no reference to moveBefore in its client build, so a keyed list reorder in React still goes through insertBefore() and an iframe inside a moved row still reloads. Do not reach past React and call moveBefore() on nodes it manages, because its reconciler expects them where it left them. If one stateful element has to survive a reorder, render it outside the list and position it with CSS. The same caution applies to custom elements rendered from React: React decides when they move, so the connectedMoveCallback hook only helps once React itself calls moveBefore().

A worked example: the sticky mini player

The clearest use is the video embed that follows you down the page. Scroll past the article’s player and the playing YouTube or Vimeo iframe moves into a fixed corner dock. With appendChild() the iframe reloads, so the embed starts again from its first frame and the viewer loses their place.

import { moveNode } from "./move.js";

const slot = document.querySelector<HTMLElement>("#player-slot")!;
const dock = document.querySelector<HTMLElement>("#dock")!;
const player = document.querySelector<HTMLIFrameElement>("#player")!;

new IntersectionObserver(([entry]) => {
  const target = entry.isIntersecting ? slot : dock;
  if (player.parentNode !== target) moveNode(target, player);
}).observe(slot);

We ran this against a local page with a srcdoc iframe that counts its own loads, scrolling it into the dock and back. Chromium and Firefox finished with one load. WebKit, on the insertBefore() fallback, finished with three: the original plus one per move. For Safari users the dock still works and the video restarts, as it always has. Give #player-slot a fixed height in CSS so the article does not jump when the iframe leaves it.

Should you switch to moveBefore now?

Yes, anywhere you relocate an iframe, a focused field, an open popover or a modal dialog, use the helper. It costs one feature check, behaves identically to insertBefore() on Safari and fixes real bugs in the two engines that support it. Drag-and-drop list reordering, moving a popover or dialog into a different container, and docking a video are the obvious places.

We would not do a blanket find-and-replace of appendChild(), though. A plain <li> with no iframe, focused field or open overlay inside it loses nothing when it is reinserted, a freshly created node is rejected by moveBefore() anyway, and any custom element without connectedMoveCallback gets the same callbacks either way. Add the hook to your own components first, then switch the call sites where state actually breaks.

If you are building an interface where this kind of state loss shows up as bug reports, it is the sort of front-end work we do in our web application development projects.

Need this built properly?

Get in touch

Hack the planet!