DEV Community

Cover image for moveBefore(): move DOM nodes without resetting them
richi.codes
richi.codes

Posted on Originally published at richi.codes

moveBefore(): move DOM nodes without resetting them

This note has an interactive demo. Try it in the original

Moving an element around the DOM has always been a small lie: the browser actually removes it and inserts it again, and everything that lives inside it starts over. Element.moveBefore() is the first real "move" in the DOM, and it already works in Chrome and Firefox.

Try the demo above before reading on. The card has three things that hate being moved: an <iframe> with its own clock, a CSS animation filling a bar, and a text field. Turn on auto-move, type in the field, and switch between moveBefore() and insertBefore(). With the first one, the clock keeps counting, the bar keeps filling and your cursor stays where it was. With the second, the iframe reloads, the animation jumps back to zero and focus is gone.

Why a move used to reset everything

appendChild(), insertBefore(), prepend() and friends don't have a "move" mode. If the node is already in the document, the browser first takes it out and then puts it back in the new place. For a plain <div> with text you never notice. For anything with state, that removal is destructive. According to MDN, moveBefore() keeps, among others:

  • animation and transition state,
  • the loading state of an <iframe>,
  • interactivity states such as :focus and :active,
  • the fullscreen element,
  • open popovers,
  • modal <dialog> elements (they don't get closed).

Chrome's announcement puts the problem plainly: framework authors spend a lot of effort on workarounds (DOM-morphing libraries, bug reports they can't fix), and users still see application state reset when they don't expect it.

How it works

Same arguments as insertBefore(): the node to move and the node to place it before, or null to put it at the end. This is the line the demo runs on every move:

// target is the other dock; null means "at the end"
if (mode() === 'move' && supported) target.moveBefore(widget, null);
else target.insertBefore(widget, null);
Enter fullscreen mode Exit fullscreen mode

It returns undefined and exists on Element, Document and DocumentFragment. There are a few rules worth knowing, because unlike insertBefore() it throws in situations you might not expect:

  • Both the node and the new parent have to be in the same document, and both connected or both disconnected. Moving a freshly created element (not yet in the page) into the page with moveBefore() throws a HierarchyRequestError.
  • The second argument is required. parent.moveBefore(node) throws a TypeError; pass null explicitly.
  • If the reference node isn't a child of the parent, you get a NotFoundError, just like insertBefore().

Because of that, and because Safari doesn't have it yet, I'd wrap it in a tiny helper that falls back to the old behaviour:

function moveNode(parent, node, ref = null) {
  if ('moveBefore' in parent) {
    try {
      parent.moveBefore(node, ref);
      return;
    } catch {
      // Not movable (e.g. a node that isn't in the page yet): fall through.
    }
  }
  parent.insertBefore(node, ref);
}
Enter fullscreen mode Exit fullscreen mode

I ran it in Chromium, Firefox and WebKit with Playwright: in the first two a focused input stays focused after the move; in WebKit it falls back to insertBefore() and loses focus, as expected. A node that isn't in the page yet goes through the catch and gets inserted normally.

Custom elements: connectedMoveCallback()

Here's a catch for web components. A plain move with insertBefore() fires disconnectedCallback() and then connectedCallback(), and since those are where most components set up and tear down, a move can wipe their state. MDN's custom elements guide says moveBefore() alone doesn't fix that: you also have to define connectedMoveCallback(). When it exists and you move the element with moveBefore(), it runs instead of the other two.

class MovableWidget extends HTMLElement {
  connectedCallback() { console.log('connected'); }
  disconnectedCallback() { console.log('disconnected'); }
  connectedMoveCallback() { console.log('moved'); }
}
customElements.define('movable-widget', MovableWidget);
Enter fullscreen mode Exit fullscreen mode

In my test, moving the element with moveBefore() logged only moved; moving it back with insertBefore() logged disconnected and connected. An empty connectedMoveCallback() is enough if all you want is to skip the teardown.

Browser support and gotchas

According to MDN's compatibility data, moveBefore() shipped in Chrome 133 (February 2025) and Firefox 144 (October 2025). Safari doesn't support it: WebKit's tracking bug is still open, with some dependencies pending. That means it isn't Baseline, so feature detection is mandatory:

const supported = 'moveBefore' in Element.prototype;
Enter fullscreen mode Exit fullscreen mode

Other things to keep in mind:

  • MutationObserver still sees a removal and an addition. MDN says so and my test agreed: one move produced one record with a removed node and another with an added node. If your code reacts to "node removed" by cleaning things up, check whether it came back.
  • It's "most" state, not all of it. The Chrome post is careful to say it preserves most state. Test the specific thing you care about.
  • The fallback is visible. In Safari, users get the old reset behaviour. That's fine for progressive enhancement, but don't build a feature that only makes sense if the iframe never reloads.

What to keep an eye on

  • Safari. WebKit bug 281223 is the one to watch; when it closes, moveBefore() is a candidate for Baseline.
  • Frameworks and libraries. Anything that reorders keyed lists or morphs HTML could switch to moveBefore() where available and stop reloading embeds and losing focus for free.
  • Your own components. If you write custom elements, adding connectedMoveCallback() now costs nothing and makes them behave in Chrome and Firefox today.

Sources


Originally published at richi.codes.

Top comments (0)