Moving and adopting elements
Learn how moveBefore moves an element without losing focus, animations, or iframes, what connectedMoveCallback should do, and when adoptedCallback runs.
- 01Move elements without resetting themUse
moveBefore()to keep focus, animations, and iframes, and know the one thing it still clears. - 02Fall back when moveBefore() can't helpKnow when it throws, and use
insertBefore()in those cases and in Safari. - 03Write components that survive any moveChoose what
connectedMoveCallback()does, and handleadoptedCallback()and documents without a window.
What happens when you move an element?
Asha's shop for Leaf and Kettle has a new Featured shelf at the top. When she features a tea, its card moves up there. Ravi's card has a Feature button, a bar that fills while the tea steeps, and a brewing video from a video site, shown in a frame.
Asha tries it with the keyboard. She tabs to Feature and presses Enter. The card moves up. But the bar starts again from empty, and the video starts from the beginning. The button isn't focused any more, so Enter does nothing. Why does a move reset the card? And can it move without that?
append() and insertBefore() move an element by taking it out of the page and putting it back. Taking it out resets what the browser kept for it, like focus, animations, and the page in a frame. moveBefore() moves it in one step, so all of that keeps going.
You met moveBefore() in lesson 3.3, connectedCallback and disconnectedCallback. This lesson goes further. It shows what a move keeps, when moveBefore() says no, and what happens when an element moves to another document. Here are two buttons that move themselves. Click Oolong, then Green:
<p id="shelf">Shelf: <button>Oolong</button> <button>Green</button></p><p id="featured">Featured: </p> <script> const [oolong, green] = document.querySelectorAll("button"); const shelf = document.querySelector("#shelf"); const featured = document.querySelector("#featured"); const other = (button) => (button.parentNode === shelf ? featured : shelf); oolong.onclick = () => { other(oolong).append(oolong); console.log("Oolong kept focus:", document.activeElement === oolong); }; green.onclick = () => { other(green).moveBefore(green, null); console.log("Green kept focus:", document.activeElement === green); }; green.disabled = !("moveBefore" in Element.prototype);</script>- Line 1 puts two buttons on the shelf.
- Line 8 makes
other(), a small helper. It gives back the shelf the button isn't on. - Lines 10 to 13 move Oolong with
append(). Line 12 prints whether Oolong still has focus. - Lines 14 to 17 move Green with
moveBefore(). It takes the same two things asinsertBefore(): the element to move, and the child to put it before.nullmeans "at the end". - Line 18 turns Green off in browsers that don't have the method, like Safari.
Focus is where your keys go: the button you clicked or tabbed to. document.activeElement is the element that has it. Clicking Oolong prints Oolong kept focus: false. Clicking Green prints Green kept focus: true.
Now press Space. Green still has focus, so it moves back to the shelf. Click Oolong and press Space, and nothing moves. Oolong lost its focus on the way.
append() takes the card off the page for a moment, so the browser resets what it was showing. moveBefore() moves it in one step.Asha wants a full cup of tea at the other end of the counter. She could pour it away and fill a fresh cup over there. Or she could slide the full cup along. Sliding keeps the same tea, still warm.
- In real life: Pouring the tea away and filling a fresh cup
- In JavaScript:
append()on an element already on the page - In real life: Sliding the full cup along the counter
- In JavaScript:
moveBefore() - In real life: The warm tea in the cup
- In JavaScript: Focus, animations, and the page in a frame
- In real life: The other end of the counter
- In JavaScript: The new parent
append() moves an element by taking it out and putting it back, and that resets it. moveBefore() moves it in one step, so focus, animations, and frames keep going. It only works within one page, and Safari doesn't have it.
What does moveBefore() keep that append() resets?
The buttons showed focus. A real card holds more. Here is Ravi's card. It has a Move button, a bar that grows for 8 seconds, and a frame with a note box. A frame, or <iframe>, shows a whole second page inside this one. Pick a way to move it:
<style> .bar { height: 8px; background: teal; animation: steep 8s linear forwards; } @keyframes steep { from { width: 0; } to { width: 100%; } }</style> <div id="shelf">Shelf: <div id="card"> Oolong <button>Move</button> <div class="bar"></div> <iframe srcdoc="<input placeholder='Type a note'>"></iframe> </div></div><div id="featured">Featured:</div> <script> const card = document.querySelector("#card"); const button = card.querySelector("button"); const shelf = document.querySelector("#shelf"); const featured = document.querySelector("#featured"); button.onclick = () => { const to = card.parentNode === shelf ? featured : shelf; to.append(card); console.log("Move kept focus:", document.activeElement === button); };</script>append() takes the card out of the page and puts it back. The bar starts again from empty, the frame loads again so your note is gone, and the Move button loses focus.
- Lines 1 to 4 make the bar grow from empty to full in 8 seconds. That's a CSS animation.
- Line 10 is the frame. Its
srcdocattribute holds the little page inside it: one text box. - Line 22 moves the card to the other shelf. The buttons above the code swap this line.
- Line 23 prints whether the Move button kept focus.
With append(), three things start over. The bar jumps back to empty. The frame loads its page again, so your note is gone. And the console prints Move kept focus: false.
With moveBefore(), the bar keeps growing and your note stays. The console prints Move kept focus: true.
Why the difference? When append() takes the card out, the browser treats it as gone. It stops the animation, throws away the frame's page, and moves focus away. Putting the card back starts them all fresh. moveBefore() never takes the card out, so nothing stops. The DOM Standard calls it a move: one step, with no removing and no inserting.
The course moved each of these both ways in Chrome. Read each row across:
| What the element has | After append() | After moveBefore() |
|---|---|---|
Focus, and :focus | Lost. Focus goes back to the page. | Kept. |
:hover, under a still mouse | Lost. | Kept. |
| A running CSS animation | Starts again from the beginning. | Keeps its place. |
| A running CSS transition | Stops and jumps to the end. | Keeps going. |
The page inside an <iframe> | Loads again from scratch. | Stays as it was. |
| An open popover | Closes. | Stays open. |
A modal <dialog> | Stays open, but isn't modal any more. | Stays modal. |
A playing <video> | Keeps playing. | Keeps playing. |
| Text the reader selected | The selection is cleared. | The selection is cleared. |
Two rows surprise people. A playing <video> keeps playing either way. MDN says media keeps playing however you move it. Asha's video started over because it sits in a frame, and the frame loaded again. And neither way keeps selected text. The DOM Standard's move steps fix up a selection the same way removing does, so it's cleared. Selection and Range explains how selections work.
Why it matters: a keyboard user who loses focus loses their place. Chrome's guide to moving elements asks you not to drop focus back to the page's <body>. A move with moveBefore() leaves it where it was. For more on focus, see Keyboard and focus.
When does moveBefore() throw an error?
append() can put an element almost anywhere. moveBefore() is stricter. Try three moves:
<p id="shelf">Shelf: <span id="oolong">Oolong</span></p><p id="featured">Featured: </p> <script> const featured = document.querySelector("#featured"); const oolong = document.querySelector("#oolong"); function tryMove(label, parent, node) { try { parent.moveBefore(node, null); console.log(label, "moved"); } catch (error) { console.log(label, error.name); } } tryMove("Oolong to Featured:", featured, oolong); tryMove("A new tea:", featured, document.createElement("span")); tryMove("Oolong into a box:", document.createElement("div"), oolong);</script>- Lines 7 to 14 make
tryMove(). It tries one move. It printsmoved, or the error's name if the move throws. - Line 15 moves Oolong from the shelf to Featured. It prints
Oolong to Featured: moved. - Line 16 moves a brand new span into Featured. It prints
A new tea: HierarchyRequestError. - Line 17 moves Oolong into a box made in script. It prints
Oolong into a box: HierarchyRequestError.
A HierarchyRequestError is the error the DOM throws when a node can't go where you asked. Chrome's message says: "State-preserving atomic move cannot be performed on nodes participating in an invalid hierarchy." In plain words, it can't keep this element's state on this trip.
The DOM Standard's first check is simple: both places must be in the same tree. A tree here means everything joined under one root:
- Everything on one page is one tree. Its root is the document.
- A box made with
createElement(), and not added anywhere, is a tree of its own. - An iframe's page is another tree, with its own document.
The new span on line 16 is a tree of its own, and so is the box on line 17. A move between the page and an iframe throws too. A move inside one box off the page works, but no callback runs, because nothing is on a page.
Two more errors come from the rules every insert has. A reference child that isn't in the parent throws a NotFoundError. Moving a parent into its own child throws a HierarchyRequestError.
moveBefore() only moves an element within one tree: the same page, or the same box off the page. The other three moves throw a HierarchyRequestError.A cup slides easily along the counter. But Asha can't slide it into the café next door. She can't slide it from the counter into a box in the storeroom either. For those trips, she picks the cup up and carries it.
- In real life: Sliding a cup along one counter
- In JavaScript:
moveBefore()within one tree - In real life: The café next door
- In JavaScript: Another document, like an iframe's
- In real life: A box in the storeroom
- In JavaScript: An element that isn't on the page
- In real life: Picking the cup up and carrying it
- In JavaScript:
insertBefore()orappend()
Falling back to insertBefore()
Safari doesn't have moveBefore(). Its engine, WebKit, keeps it behind a setting that's off by default. So code that moves things needs a plan B, like taking the stairs when the lift is broken. MDN suggests insertBefore(), or a try...catch. Ravi writes a small helper that does both:
<p id="shelf">Shelf: <span id="oolong">Oolong</span></p><p id="featured">Featured: </p> <script> function move(parent, node, before = null) { if ("moveBefore" in parent) { try { parent.moveBefore(node, before); return "moveBefore"; } catch (error) { if (error.name !== "HierarchyRequestError") throw error; } } parent.insertBefore(node, before); return "insertBefore"; } const featured = document.querySelector("#featured"); console.log(move(featured, document.querySelector("#oolong"))); const green = document.createElement("span"); green.textContent = " Green"; console.log(move(featured, green));</script>- Line 6 checks that this browser has
moveBefore(). In Safari, it skips to line 14. - Line 8 tries the move. Line 9 says which method worked.
- Line 11 lets other errors through. A
NotFoundErroris a real bug, andinsertBefore()would throw it too. - Lines 14 and 15 do a plain insert.
- Line 19 moves Oolong, which is on the page. It prints
moveBefore. - Line 22 adds a new span.
moveBefore()throws, so it printsinsertBefore.
In Safari, both lines print insertBefore. The tea still gets there. It just starts over, as with append().
Why it matters: with this helper, a page moves things the best way each browser allows, and never breaks.
Now sort these moves. Which ones does moveBefore() do, and which ones throw?
featured.moveBefore(oolong, null), with both on the pagefeatured.moveBefore(shelf.firstChild, null), where the first child is textbox.moveBefore(green, null), wheregreenis already inside the box, and the box isn't on the pagefeatured.moveBefore(document.createElement("span"), null)box.moveBefore(oolong, null), for a box made withcreateElement()template.content.moveBefore(oolong, null)frame.contentDocument.body.moveBefore(oolong, null)
Sort each call by what Chrome does with it.
What should connectedMoveCallback do?
Lesson 3.3 showed the switch. A custom element with a connectedMoveCallback() method gets only that call when moveBefore() moves it. Without one, moveBefore() still runs disconnectedCallback(), then connectedCallback(). The HTML Standard keeps that default, so components written before moveBefore() work as before.
So what goes inside it? Here is a badge that says which shelf it sits on. It prints Started when it joins the page, as if it started a timer. Try each version:
<p id="shelf" data-name="the shelf">Shelf: <tea-badge></tea-badge></p><p id="featured" data-name="the featured shelf">Featured: </p> <script src="tea-badge.js"></script> <script> const badge = document.querySelector("tea-badge"); const featured = document.querySelector("#featured"); if ("moveBefore" in Element.prototype) { featured.moveBefore(badge, null); } else { featured.append(badge); }</script>Without the method, moveBefore() runs disconnectedCallback(), then connectedCallback(). The badge stops and starts again, as if it had left the page.
- Lines 2 to 5 of
tea-badge.js, in the second tab, start the badge and show its place. - Lines 7 to 9 stop it.
- Lines 11 to 14 are
connectedMoveCallback(), in the last version. They only show the new place. #place()reads the place from the parent'sdata-nameattribute.- On the page, line 10 moves the badge to Featured with
moveBefore().
Without the method, the console prints Stopped, then Started on the featured shelf. The badge stopped and started again. With an empty method, it prints only Started on the shelf. But the badge still says Oolong, on the shelf, which is out of date. With the method that updates, it prints Moved to the featured shelf, and the words match.
That gives three choices:
- Leave it out when starting again is cheap and harmless. The kit's
tea-labelonly sets its words, so a restart costs nothing. - Write an empty one when the element must keep going, and nothing depends on where it sits. The kit's
tea-timerhas one. - Put work in it when something depends on the new place, like the parent or a shelf name. The HTML Standard's own example does this. Don't start timers or add listeners there. They are still running.
A guest at table 2 asks to sit by the window, at table 6. The waiter carries her teapot over. She doesn't brew a new pot, and she doesn't pour the old one away. She only changes the table number on the order slip.
- In real life: The guest moving to another table
- In JavaScript:
moveBefore()moving the element - In real life: Not brewing a new pot
- In JavaScript: Not running setup again
- In real life: Changing the table number on the slip
- In JavaScript: Work in
connectedMoveCallback()that needs the new place - In real life: A guest who leaves the shop
- In JavaScript:
disconnectedCallback()
Elements inside the moved element
When moveBefore() moves an element, every custom element inside it moves too. Each one gets its own callbacks, and each class decides for itself. A shelf without connectedMoveCallback() gets the other two. A badge inside it, with one, gets only that. The quiz has this case.
When a page moves your element with append()
A component can't choose how pages move it. Many pages use append(), and in Safari every move is like that. Then your element gets disconnectedCallback() and connectedCallback(), one right after the other.
Frameworks have long guessed. Angular's custom elements wait 10 ms before they clean up, in case the element comes back. Nolan Lawson describes a shorter wait: one microtask. A microtask is a small job the browser runs as soon as the current code finishes. He found that Solid, Svelte, and Vue all wait this way when they build custom elements. The kit's timer does it at the end of this lesson.
Where moveBefore() exists, connectedMoveCallback() ends the guessing. The browser says "moved", so your element doesn't have to guess.
When does adoptedCallback run?
So far, every move stayed in one page. But every element belongs to one document, and pages aren't the only documents. An element's ownerDocument property says which one it belongs to. You meet other documents often:
- Each
<iframe>holds its own document. - A
<template>'scontentbelongs to a hidden document of its own. That's how a template's insides stay off the page. document.implementation.createHTMLDocument()makes a new, empty document in script. Nothing shows it on screen.
When an element moves into a different document, the browser calls its adoptedCallback(). The DOM Standard calls this adopting: the new document adopts the element. The callback gets two arguments, the old document and the new one.
The town library has two branches. When a book moves to the other branch, a librarian stamps it with the new branch's name. Its pages stay the same. From then on, it belongs to the new branch.
- In real life: The book
- In JavaScript: The element, with its class and fields
- In real life: The branch stamp inside it
- In JavaScript:
ownerDocument - In real life: The librarian stamping it
- In JavaScript:
adoptedCallback()running - In real life: The old and new branch names
- In JavaScript: The
oldDocumentandnewDocumentarguments
Ravi keeps a spare badge in a <template>, like a storeroom. Watch what runs:
<p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p><template id="storeroom"></template> <script src="tea-badge.js"></script> <script> const badge = document.querySelector("tea-badge"); const storeroom = document.querySelector("#storeroom").content; console.log("Into the storeroom"); storeroom.append(badge); console.log("Back to the shelf"); document.querySelector("#shelf").append(badge);</script>- Lines 8 to 10 of
tea-badge.js, the second tab, areadoptedCallback(). It prints whether the new document is this page. - Line 8 of the page takes the template's
content, the part that holds its insides. - Line 10 moves the badge into the storeroom. It prints
disconnectedCallback, thenadoptedCallback, into this page: false. The badge left the page and changed documents. - Line 12 brings it back to the shelf. It prints
adoptedCallback, into this page: true, thenconnectedCallback.
Notice what didn't run on line 10: connectedCallback(). The template's content isn't in a page, so nothing connected. Stage 3, Shadow DOM, templates, and slots, covers templates in full.
Now Ravi builds a receipt. createHTMLDocument() makes a new document with a <body>, and line 7 moves the badge into it:
<p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p> <script src="tea-badge.js"></script> <script> const receipt = document.implementation.createHTMLDocument("Receipt"); receipt.body.append(document.querySelector("tea-badge")); console.log("In the receipt:", receipt.body.textContent); console.log("The receipt has a window:", receipt.defaultView !== null);</script>- Line 6 makes the receipt.
"Receipt"is its title. - Line 7 moves the badge into the receipt's body. The console prints
disconnectedCallback,adoptedCallback, into this page: false, andconnectedCallback. - Line 8 prints
In the receipt: Oolong. Line 9 printsThe receipt has a window: false.
adoptedCallback() runs between leaving and joining, and it gets both documents.The DOM Standard sets this order. To add the badge, append() first adopts it, and adopting takes it out of its old parent. So disconnectedCallback() runs, then adoptedCallback(), then connectedCallback().
Line 9 holds a surprise. The receipt has no window: nothing shows it. Yet connectedCallback() ran. To the browser, an element is connected when it's inside a document, any document.
Moving into an iframe
An iframe's page is the case people meet most. The result frames on this page are locked down for safety, so they can't reach into an iframe. Run this one on the dev server from lesson 1.4, with the same tea-badge.js:
<p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p>
<script src="tea-badge.js"></script>
<script>
const frame = document.createElement("iframe");
frame.srcdoc = "<p>Receipt</p>";
frame.onload = () => {
const badge = document.querySelector("tea-badge");
frame.contentDocument.body.append(badge);
console.log("Still a TeaBadge:", badge instanceof TeaBadge);
console.log("Defined in the frame:", frame.contentWindow.customElements.get("tea-badge"));
};
document.body.append(frame);
</script>- Lines 6 and 7 make a frame whose page says Receipt.
- Line 8 waits for the frame's page to load. Line 14 adds the frame to the page, which starts the loading.
- Line 10 moves the badge into the frame's
<body>. The same three callbacks run. - Line 11 prints
Still a TeaBadge: true. - Line 12 prints
Defined in the frame: undefined.
Each window has its own registry, and the frame never defined tea-badge. But the badge keeps the class it already has, so its callbacks still run. A new tea-badge made in the frame would be a plain element. Each window also has its own built-ins, as Realms and globals shows.
moveBefore() can't make this trip. It throws a HierarchyRequestError, as the last section showed. Every move between documents takes the element out and puts it in.
Real pages do this. Chrome's Document Picture-in-Picture docs move a video player into a small floating window with append(). When that window closes, they move it back.
Writing components that can change documents
A component that can land in another document needs two habits.
Using this.ownerDocument instead of document
Inside a class, document always means the page where the class was written. this.ownerDocument means the document the element is in right now. After a move, they differ:
<p>Tips go on the receipt.</p> <script> class TeaTip extends HTMLElement { connectedCallback() { document.addEventListener("click", () => console.log("Heard on document")); this.ownerDocument.addEventListener("click", () => console.log("Heard on ownerDocument")); } } customElements.define("tea-tip", TeaTip); const receipt = document.implementation.createHTMLDocument("Receipt"); receipt.body.append(new TeaTip()); console.log("A click in the receipt:"); receipt.body.click();</script>- Line 6 listens for clicks on
document. - Line 7 listens on
this.ownerDocument. - Line 13 puts a new tip into the receipt. Its
connectedCallback()runs there, sothis.ownerDocumentis the receipt. - Line 15 clicks the receipt's body. The console prints
Heard on ownerDocument, and nothing from line 6.
Line 6 listens to the wrong document. On a real page, that's a tip that never closes after a move, or a key that does nothing.
Ravi lends a waiter to the café next door for the day. If she keeps listening for her own shop's bell, she never hears the customers in front of her. So she listens for the bell in the café where she works today.
- In real life: Her own shop's bell
- In JavaScript:
document, the page where the class was written - In real life: The bell where she works today
- In JavaScript:
this.ownerDocument - In real life: Lending her to the café
- In JavaScript: Moving the element into another document
Check for a window before you use one
The receipt printed The receipt has a window: false. Its defaultView, the window that shows it, is null. So code like this.ownerDocument.defaultView.matchMedia(…) throws there. The HTML Standard's first example gives the advice. Check this.ownerDocument.defaultView before work that needs a window, and skip the work if there isn't one. Exercise 6 has this bug.
adoptNode() and importNode()
Two more methods bring an element into a document. adoptNode() moves the real element. importNode() makes a copy:
<p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p> <script src="tea-badge.js"></script> <script> const receipt = document.implementation.createHTMLDocument("Receipt"); const badge = document.querySelector("tea-badge"); const copy = receipt.importNode(badge, true); console.log("The copy is a TeaBadge:", copy instanceof TeaBadge); const moved = receipt.adoptNode(badge); console.log("adoptNode() gave back the badge:", moved === badge); console.log("Badges on the page:", document.querySelectorAll("tea-badge").length);</script>- Line 8 makes a copy of the badge in the receipt. The badge stays on the shelf.
- Line 9 prints
The copy is a TeaBadge: false. The receipt never definedtea-badge, so the copy is a plain element. - Line 10 moves the badge itself. It prints
disconnectedCallbackandadoptedCallback, into this page: false. NoconnectedCallback: an adopted element has no parent yet. - Line 11 prints
adoptNode() gave back the badge: true. Line 12 printsBadges on the page: 0.
Here are the three ways side by side. Read each row across:
| What the code does | What happens to the badge |
|---|---|
receipt.body.append(badge) | Moves the badge into the receipt. disconnectedCallback(), adoptedCallback(), and connectedCallback() run, in that order. |
receipt.adoptNode(badge) | Moves the badge into the receipt without a parent. disconnectedCallback() and adoptedCallback() run. |
receipt.importNode(badge, true) | Makes a copy in the receipt, and the badge stays on the page. The copy is a plain element, because the receipt never defined tea-badge. |
Why it matters: to move a component, use append() or adoptNode(). A copy made in a document that never defined its tag is a plain element, not your component.
Keeping the kit's timer running on every move
The kit's tea-timer from lesson 3.3 has an empty connectedMoveCallback(). So moveBefore() keeps it counting. But append() still starts it again from its first number, and Safari only has append(). Ravi adds the microtask wait from earlier. Press Brew, then try every button:
<script type="importmap"> { "imports": { "tea-kit/": "./tea-kit/" } }</script> <p id="shelf">Shelf: </p><p id="featured">Featured: </p><button id="brew">Brew</button><button id="append">Move with append()</button><button id="move">Move with moveBefore()</button><button id="serve">Serve</button> <script type="module"> import "tea-kit/index.js"; const timer = document.createElement("tea-timer"); timer.setAttribute("seconds", "5"); const [shelf, featured] = document.querySelectorAll("p"); const other = () => (timer.parentNode === shelf ? featured : shelf); document.querySelector("#brew").onclick = () => shelf.append(timer); document.querySelector("#append").onclick = () => other().append(timer); document.querySelector("#move").onclick = () => other().moveBefore(timer, null); document.querySelector("#move").disabled = !("moveBefore" in Element.prototype); document.querySelector("#serve").onclick = () => timer.remove();</script>- Line 13 loads the whole kit, with the new
tea-timer.js. - Lines 20 and 21 move the timer to the other shelf, with
append()or withmoveBefore(). - Line 23 serves the tea. It removes the timer for good.
Now open the tea-kit/tea-timer.js tab:
- Line 2 starts
#controlleratnull. - Line 5 is a guard. If there's a controller, the timer is already running, so it returns.
- Lines 17 and 18 make
disconnectedCallback()wait one microtask.await Promise.resolve()is the shortest wait there is. - Line 19 checks
isConnectedafter the wait. If the timer is back on the page, it was only a move, so nothing stops. - Lines 20 and 21 stop the timer and clear the controller, so the next join starts fresh.
- Line 24 keeps the empty
connectedMoveCallback(), somoveBefore()runs no callback at all.
Press Brew and wait two seconds: the timer shows 3 s. Move it with append(). It stays at 3 s and keeps counting. Lesson 3.3's version started again at 5 s. Move it with moveBefore(), and it keeps counting too. Press Serve, then Brew, and a new count starts at 5 s.
The kit's other files stay as they were in lesson 3.4. The kit gains two rules:
- Move kit elements with
moveBefore()where you can, and fall back toinsertBefore(). - A component that must survive any move waits a microtask before it cleans up, and never starts twice.
Asha's Featured shelf works now. A tea moves up, and its timer keeps counting, in every browser.
Common mix-ups
- "
moveBefore()keeps everything." No. It clears selected text, asappend()does. And a custom element withoutconnectedMoveCallback()still stops and starts. - "
moveBefore()works whereverappend()does." No. It throws for a new element, for a move between documents, and for a move between the page and a place off it. - "
adoptedCallback()runs when an element moves on the page." No. It runs only when the element changes documents. - "A playing video stops when
append()moves it." No. Video and audio keep playing however you move them. - "An element moved into an iframe needs the iframe to define its tag." No. It keeps the class it has. Only new tags made in the frame need a definition there.
- "
connectedMoveCallback()should start the timer again." No. Nothing stopped it. Starting again would run two timers. - "Inside a class,
documentis the element's document." No. It's the page where the class was written. Usethis.ownerDocument. - "
connectedCallback()means the element is on screen." No. It runs in any document, even one with no window.
Practice exercises
Answer first, then use the hints. The solutions run live, so you can check yourself.
This page uses the adoption examples' tea-badge.js. How many times does adoptedCallback() run?
<p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p>
<script src="tea-badge.js"></script>
<script>
const badge = document.querySelector("tea-badge");
const receipt = document.implementation.createHTMLDocument("Receipt");
receipt.body.append(badge);
receipt.body.append(badge);
document.querySelector("#shelf").append(badge);
</script><p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p> <script src="tea-badge.js"></script> <script> const badge = document.querySelector("tea-badge"); const receipt = document.implementation.createHTMLDocument("Receipt"); receipt.body.append(badge); receipt.body.append(badge); document.querySelector("#shelf").append(badge);</script>Twice. Line 8 moves the badge from the page into the receipt, and line 10 moves it back. Line 9 moves it within the receipt, so it only leaves and joins again.
How many of the three moves work?
<p id="shelf">Shelf: <span id="oolong">Oolong</span></p>
<p id="featured">Featured: </p>
<script>
const oolong = document.querySelector("#oolong");
const featured = document.querySelector("#featured");
const box = document.createElement("div");
const green = document.createElement("span");
box.append(green);
const moves = [
() => featured.moveBefore(oolong, null),
() => box.moveBefore(green, null),
() => featured.moveBefore(green, null),
];
for (const move of moves) {
try {
move();
console.log("moved");
} catch (error) {
console.log(error.name);
}
}
</script><p id="shelf">Shelf: <span id="oolong">Oolong</span></p><p id="featured">Featured: </p> <script> const oolong = document.querySelector("#oolong"); const featured = document.querySelector("#featured"); const box = document.createElement("div"); const green = document.createElement("span"); box.append(green); const moves = [ () => featured.moveBefore(oolong, null), () => box.moveBefore(green, null), () => featured.moveBefore(green, null), ]; for (const move of moves) { try { move(); console.log("moved"); } catch (error) { console.log(error.name); } }</script>Two. Line 11 moves Oolong within the page. Line 12 moves Green within the same box. Line 13 moves Green from the box onto the page, so it throws a HierarchyRequestError.
Type a note and press Enter. What does the console print? Then fix it, so you can keep typing.
<div id="shelf">Shelf: <p id="card">Oolong <input placeholder="Type a note, then press Enter"></p></div><div id="featured">Featured:</div> <script> const card = document.querySelector("#card"); const input = card.querySelector("input"); input.addEventListener("keydown", (event) => { if (event.key !== "Enter") return; document.querySelector("#featured").append(card); console.log("Still typing:", document.activeElement === input); });</script><div id="shelf">Shelf: <p id="card">Oolong <input placeholder="Type a note, then press Enter"></p></div><div id="featured">Featured:</div> <script> const card = document.querySelector("#card"); const input = card.querySelector("input"); input.addEventListener("keydown", (event) => { if (event.key !== "Enter") return; document.querySelector("#featured").moveBefore(card, null); console.log("Still typing:", document.activeElement === input); });</script>The starter prints Still typing: false. append() takes the card off the page, and the text box loses focus. With moveBefore(), it prints Still typing: true, and you can keep typing.
Fill in the function. What should the page print in Chrome?
<p id="featured">Featured: </p> <script> function move(parent, node) { // Use moveBefore() when it works, and insertBefore() when it doesn't. // Return the name of the method that moved the node. } const featured = document.querySelector("#featured"); const green = document.createElement("span"); green.textContent = "Green"; console.log(move(featured, green));</script><p id="featured">Featured: </p> <script> function move(parent, node) { if ("moveBefore" in parent) { try { parent.moveBefore(node, null); return "moveBefore"; } catch (error) { if (error.name !== "HierarchyRequestError") throw error; } } parent.insertBefore(node, null); return "insertBefore"; } const featured = document.querySelector("#featured"); const green = document.createElement("span"); green.textContent = "Green"; console.log(move(featured, green));</script>It prints insertBefore. The new Green span has never been on the page, so moveBefore() throws a HierarchyRequestError, and the helper inserts it instead.
How many times does the starter print Started? Then change the class, so the two moves don't start it again.
<p id="shelf">Shelf: </p><p id="featured">Featured: </p> <script> class TeaBrew extends HTMLElement { connectedCallback() { console.log("Started"); } disconnectedCallback() { console.log("Stopped"); } } customElements.define("tea-brew", TeaBrew); const brew = document.createElement("tea-brew"); document.querySelector("#shelf").append(brew); document.querySelector("#featured").append(brew); document.querySelector("#shelf").append(brew);</script><p id="shelf">Shelf: </p><p id="featured">Featured: </p> <script> class TeaBrew extends HTMLElement { #running = false; connectedCallback() { if (this.#running) return; this.#running = true; console.log("Started"); } async disconnectedCallback() { await Promise.resolve(); if (this.isConnected) return; this.#running = false; console.log("Stopped"); } } customElements.define("tea-brew", TeaBrew); const brew = document.createElement("tea-brew"); document.querySelector("#shelf").append(brew); document.querySelector("#featured").append(brew); document.querySelector("#shelf").append(brew);</script>The starter prints Started three times: once for line 16 and once after each move. The fix waits a microtask before stopping. By then the brew is back on the page, so it never stops, and Started prints once.
What kind of error does the starter throw? Then fix the class, so it works in any document.
<p id="shelf">Shelf: <tea-size>Oolong</tea-size></p> <script> class TeaSize extends HTMLElement { connectedCallback() { const view = this.ownerDocument.defaultView; const wide = view.matchMedia("(min-width: 400px)").matches; this.dataset.size = wide ? "wide" : "narrow"; console.log(`${this.textContent} is ready`); } } customElements.define("tea-size", TeaSize); const receipt = document.implementation.createHTMLDocument("Receipt"); receipt.body.append(document.querySelector("tea-size"));</script><p id="shelf">Shelf: <tea-size>Oolong</tea-size></p> <script> class TeaSize extends HTMLElement { connectedCallback() { const view = this.ownerDocument.defaultView; if (!view) return; const wide = view.matchMedia("(min-width: 400px)").matches; this.dataset.size = wide ? "wide" : "narrow"; console.log(`${this.textContent} is ready`); } } customElements.define("tea-size", TeaSize); const receipt = document.implementation.createHTMLDocument("Receipt"); receipt.body.append(document.querySelector("tea-size"));</script>A TypeError. In the receipt, defaultView is null, so line 7 reads matchMedia from null. The fix skips the work when there's no window.
Check your understanding
For each question, ask two things: did the element leave its tree, and did it change documents?
Question 1 of 8What does
append()do with an element that's already on the page?Choose an answer to see the explanation.
Question 2 of 8Which of these does
moveBefore()keep?Choose an answer to see the explanation.
Question 3 of 8What happens when you call
featured.moveBefore(document.createElement("span"), null)?Choose an answer to see the explanation.
Question 4 of 8This page uses the adoption examples' tea-badge.js. What does it print after
connectedCallback?Read the code, then predict<p id="shelf">Shelf: <tea-badge>Oolong</tea-badge></p> <template id="storeroom"></template> <script src="tea-badge.js"></script> <script> const badge = document.querySelector("tea-badge"); document.querySelector("#storeroom").content.append(badge); </script>Choose an answer to see the explanation.
Question 5 of 8What does this page print after
Moving?Read the code, then predict<div id="featured"></div> <tea-shelf><tea-badge></tea-badge></tea-shelf> <script> customElements.define("tea-shelf", class extends HTMLElement { connectedCallback() { console.log("shelf connected"); } disconnectedCallback() { console.log("shelf disconnected"); } }); customElements.define("tea-badge", class extends HTMLElement { connectedMoveCallback() { console.log("badge moved"); } }); console.log("Moving"); const featured = document.querySelector("#featured"); featured.moveBefore(document.querySelector("tea-shelf"), null); </script>Choose an answer to see the explanation.
Question 6 of 8When does the browser call
adoptedCallback()?Choose an answer to see the explanation.
Question 7 of 8A component calls
document.addEventListener()inconnectedCallback(). Then it's moved into an iframe. Which document does that listener hear?Choose an answer to see the explanation.
Question 8 of 8What should a timer's
connectedMoveCallback()do?Choose an answer to see the explanation.
Key takeaways
append()andinsertBefore()move an element by removing it and inserting it again. That resets focus, animations, transitions, frames, open popovers, and modal dialogs.moveBefore()moves in one step and keeps them. Selected text is cleared either way, and video plays on either way.moveBefore()only moves within one tree. Otherwise it throws aHierarchyRequestError. Fall back toinsertBefore(), as Safari always must.connectedMoveCallback()opts a custom element in. Leave it empty to keep going, or update only what depends on the new place.adoptedCallback(oldDocument, newDocument)runs only when an element changes documents, betweendisconnectedCallback()andconnectedCallback().- Use
this.ownerDocument, notdocument, and checkdefaultViewbefore you use a window.
Remember the one-liner.
Slide elements with moveBefore() when you can, and build components that survive being carried.
Sources
The facts on this page come from these standards, docs, and source files:
- Element: moveBefore() method, MDN.
- Preserve state during DOM mutations with moveBefore(), Dominic Farolino, Chrome for Developers.
- Modern Web Guidance: Move DOM element without losing state, Chrome for Developers.
- DOM Standard: moveBefore(), WHATWG.
- DOM Standard: Move, WHATWG.
- moveBefore() feature status, webstatus.dev.
- MoveBeforeEnabled in UnifiedWebPreferences.yaml, at WebKit-7625.2.8, WebKit.
- Using custom elements: Lifecycle callbacks and state-preserving moves, MDN.
- HTML Standard: Preserving custom element state when moved, WHATWG.
- HTML Standard: Enqueue a custom element callback reaction, WHATWG.
- component-factory-strategy.ts, at Angular v22.2.5, Angular.
- Avoiding unnecessary cleanup work in disconnectedCallback, Nolan Lawson.
- DOM Standard: Adopt, WHATWG.
- HTMLTemplateElement: content property, MDN.
- DOMImplementation: createHTMLDocument() method, MDN.
- Node: ownerDocument property, MDN.
- HTML Standard: Creating an autonomous custom element, WHATWG.
- Document: adoptNode() method, MDN.
- Document: importNode() method, MDN.
- Picture-in-Picture for any Element, not just video, Chrome for Developers.
Coming next: The custom element lifecycle in order. Step through every callback in the order the browser calls it.