12k
All articles

Moving DOM Nodes Without Losing State

See how Element.moveBefore() preserves iframe, focus, animation and dialog state when moving DOM nodes, with syntax, constraints, custom element hooks and fallbacks.

OpenReplay Team
OpenReplay Team
Moving DOM Nodes Without Losing State

Element.moveBefore() moves a node that is already in the document without the remove-then-insert step that appendChild() and insertBefore() perform, so an <iframe> keeps its loaded page, a focused input keeps focus, and a running CSS animation keeps running.

Most developers who reparent live elements have hit this: you drag a card to a new column and the embedded player inside it goes blank and reloads, or the field you were typing in loses focus partway through a word.

Chrome shipped moveBefore() in Chrome 133, and the feature appears in the Chrome 133 release notes as “DOM state-preserving move”. This article covers the syntax, a demo, the exact list of preserved state, the error cases, custom element hooks and a safe fallback. If you need a refresher on the basics first, see working with the DOM in JavaScript and the life cycle of DOM elements.

Key Takeaways

  • parent.moveBefore(node, ref) takes the same arguments as insertBefore() but moves the node without removing and re-inserting it, so iframes, focus, animations, popovers and modal dialogs keep their state.
  • The moved node must be an Element or CharacterData node. Moves between documents, between connected and disconnected trees, or into the node’s own descendant throw HierarchyRequestError.
  • A MutationObserver still sees a moveBefore() move as one removal and one addition.
  • Custom elements that define connectedMoveCallback() get that callback instead of disconnectedCallback() and connectedCallback().
  • Safari does not support moveBefore(), so check 'moveBefore' in Element.prototype and fall back to insertBefore().

Why Do appendChild and insertBefore Reset State?

Every move made with appendChild() or insertBefore() is really two operations: the browser removes the node from the document and then inserts it again. The Chrome team’s launch post points out that the DOM has had no other way to move a node since its early standards. Removing a node tears down state that only exists while the node is connected. An iframe unloads and reloads its document, a focused element loses focus, CSS animations start over, and open popovers and modal dialogs close.

In session replays of reorderable dashboards, the bug usually looks like this: a user drags a card, carries on typing, and the keystrokes don’t land because the field lost focus. Embedded iframes visibly reload in the middle of the session.

moveBefore() Syntax

moveBefore() takes the same two arguments as insertBefore(): the node to move and a reference node. Passing null as the reference moves the node to the end of the parent’s children.

parent.moveBefore(movedNode, referenceNode);
parent.moveBefore(movedNode, null); // append

According to MDN’s moveBefore() reference, the moved node must be an Element or a CharacterData node. Text nodes are allowed, but document types, for example, are not. The method also exists on Document and DocumentFragment, so you can move nodes inside a fragment even though a fragment is never connected to the document. The method is defined in the DOM Living Standard.

Demo: Moving an iframe With and Without moveBefore

The quickest way to see the difference is an iframe with its own internal state. This demo uses srcdoc, so it makes no network request.

<div id="left" class="box">
  <iframe id="frame" srcdoc="<button onclick='this.textContent=++n'>0</button><script>let n=0</script>"></iframe>
</div>
<div id="right" class="box"></div>
<button id="viaInsert">Move with insertBefore()</button>
<button id="viaMove">Move with moveBefore()</button>
<script>
  const frame = document.getElementById('frame');
  const left = document.getElementById('left');
  const right = document.getElementById('right');
  const target = () => (frame.parentElement === left ? right : left);

  document.getElementById('viaInsert').onclick = () =>
    target().insertBefore(frame, null); // iframe reloads, counter back to 0

  document.getElementById('viaMove').onclick = () =>
    target().moveBefore(frame, null);   // counter value survives
</script>

Click the counter inside the frame a few times, then try each button. insertBefore() reloads the frame and the counter goes back to zero. moveBefore() keeps the count. The second button only works in a browser that supports the method (see the feature detection section below).

Focus behaves the same way:

const input = document.querySelector('#note');
input.focus();
sidebar.moveBefore(input, null);
console.log(document.activeElement === input); // true
// With sidebar.insertBefore(input, null), focus is lost

What State Does moveBefore() Preserve?

moveBefore() keeps a specific set of states, listed on MDN. It does not keep every possible state:

  • Animation and transition state
  • <iframe> loading state
  • :focus and :active
  • Fullscreen element state
  • Popover open state
  • Modal <dialog> state

Native <video> and <audio> elements keep their play state even when moved with appendChild() or insertBefore(). So for media, moveBefore() matters when the player is embedded in an <iframe>, such as a third-party video embed, and not for native media elements.

moveBefore() Errors and Constraints

moveBefore() is stricter than insertBefore(). It throws in cases where insertBefore() would quietly do a remove-and-insert.

ErrorTriggered whenWhat to do
HierarchyRequestErrorMoving between a connected and a disconnected treeUse insertBefore()
HierarchyRequestErrorMoving between documentsUse insertBefore() (or adoptNode() first)
HierarchyRequestErrorMoving a node into its own descendantFix the target: this is a logic bug
HierarchyRequestErrormovedNode is not an Element or CharacterDataUse insertBefore()
NotFoundErrorreferenceNode is not a child of the parentPass a real child or null
TypeErrorThe second argument is missingPass null explicitly to append

The TypeError row catches people out because insertBefore() habits carry over: you cannot append by calling moveBefore(node) with only one argument.

MutationObserver and connectedMoveCallback

A MutationObserver still records a node moved with moveBefore() as one removed node and one added node, so existing observers keep receiving records for moves. The DOM Standard’s move steps queue a removal record for the old parent and an addition record for the new one. Code that treats a removal as “destroyed” needs another signal if it should tell moves apart from deletions. For observer setup, see the three DOM observer APIs.

Custom elements get a dedicated move hook, connectedMoveCallback(). As MDN’s custom elements guide explains, when connectedMoveCallback() is defined, it is called instead of connectedCallback() and disconnectedCallback() each time the element is moved to a different place in the DOM via Element.moveBefore().

class DashCard extends HTMLElement {
  connectedCallback()     { /* initial setup: subscriptions, timers */ }
  disconnectedCallback()  { /* teardown */ }
  connectedMoveCallback() { /* runs instead of the two above on moveBefore() */ }
}
customElements.define('dash-card', DashCard);

If the class doesn’t define connectedMoveCallback(), a moveBefore() move still runs disconnectedCallback() and then connectedCallback(). Defining the method, even as an empty function, replaces that pair. The HTML specification covers this behavior.

Feature Detection and Fallback for moveBefore

Check 'moveBefore' in Element.prototype before calling the method. Fall back to insertBefore() when the method is missing, and also when it throws a HierarchyRequestError for a move that insertBefore() would accept. Per caniuse, Chrome and Edge 133+ and Firefox 144+ support it, and Safari does not. web-features lists it as Limited availability rather than Baseline.

function moveNode(parent, node, ref = null) {
  if ('moveBefore' in Element.prototype) {
    try {
      parent.moveBefore(node, ref);
      return;
    } catch (err) {
      if (err.name !== 'HierarchyRequestError') throw err; // NotFoundError etc. are real bugs
    }
  }
  const active = document.activeElement;
  parent.insertBefore(node, ref); // state-resetting path
  if (active && node.contains(active)) active.focus();
}

The insertBefore() fallback still reloads iframes, restarts animations and closes dialogs, exactly as insertBefore() always has. Restoring focus only puts focus back, and caret position is not guaranteed. This check covers Element parents only. It does not tell you whether Document or DocumentFragment support the method.

Conclusion

moveBefore() gives the DOM a true move for the first time: one call that keeps iframes loaded, focus in place and animations running, as long as you stay inside the constraints MDN lists. Find every appendChild() or insertBefore() call in your drag-and-drop or morphing code that moves a live node, send it through a helper like moveNode(), and add connectedMoveCallback() to any custom element whose setup shouldn’t run again when it’s repositioned.

FAQs

Can moveBefore() move an element into or out of a shadow root?

Yes. ShadowRoot inherits from DocumentFragment, so it has its own moveBefore() method. The move must stay within the same shadow-including root, and a connected shadow root meets that requirement for any node connected to the same document. Moving light DOM content into a connected shadow tree keeps focus, iframe loading state and the other states MDN lists.

Why does moveBefore() throw when I insert a newly created element?

An element made with document.createElement() is not connected to the document yet. Moving a disconnected node into a connected parent throws a HierarchyRequestError. Use appendChild() or insertBefore() for the first insertion. A node that has never been connected has no iframe, focus or animation state to keep, so nothing is lost. Use moveBefore() only for moves after that.

Can moveBefore() be polyfilled for Safari?

No. A polyfill can add a moveBefore() method that calls insertBefore(), but that only copies the method name. The browser engine keeps iframe documents, focus, animations and open popovers alive during the move, and JavaScript cannot do that. In browsers without native support, a shim behaves exactly like insertBefore() and resets the same state.

Do any libraries already use moveBefore()?

Yes. htmx added moveBefore() support in version 2.0.3, released in October 2024. When the browser exposes moveBefore(), htmx uses it to move elements marked with hx-preserve during content swaps, so those elements keep their state. In browsers without the method, htmx goes back to its normal behavior, which moves elements the old remove-and-insert way.

Understand every bug

Uncover frustrations, understand bugs and fix slowdowns like never before with OpenReplay — self-hosted, with full data ownership.

Star on GitHub

We use cookies to improve your experience. By using our site, you accept cookies.