completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Moving and adopting elements

Learn how moveBefore moves an element without losing focus, animations, or iframes, what connectedMoveCallback should do, and when adoptedCallback runs.

By the end, you can
  • 01
    Move elements without resetting themUse moveBefore() to keep focus, animations, and iframes, and know the one thing it still clears.
  • 02
    Fall back when moveBefore() can't helpKnow when it throws, and use insertBefore() in those cases and in Safari.
  • 03
    Write components that survive any moveChoose what connectedMoveCallback() does, and handle adoptedCallback() 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:

Two buttons that move themselves, two waysPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 as insertBefore(): the element to move, and the child to put it before. null means "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.

Two ways to move the Oolong card from the shelf to Featured. With append(), the card goes from the shelf, off the page, then on to Featured, and its focus, animation, and frame start over. With moveBefore(), it goes straight from the shelf to Featured, and they keep going.append()on the shelfoff the pageon Featuredfocus, animation, and frame start overmoveBefore()on the shelfon Featuredfocus, animation, and frame keep going
append() takes the card off the page for a moment, so the browser resets what it was showing. moveBefore() moves it in one step.
Real-life analogySliding a full cup instead of pouring it out

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
The main idea

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:

Playground: what does the move keep?
A tea card that moves itselfPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The card starts over

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.

Pick how line 22 moves the card. Then type a note in the frame, wait for the bar to grow, and press Move. Each choice runs in a fresh page.
  • 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 srcdoc attribute 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 a move keeps
What the element hasAfter append()After moveBefore()
Focus, and :focusLost. Focus goes back to the page.Kept.
:hover, under a still mouseLost.Kept.
A running CSS animationStarts again from the beginning.Keeps its place.
A running CSS transitionStops and jumps to the end.Keeps going.
The page inside an <iframe>Loads again from scratch.Stays as it was.
An open popoverCloses.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 selectedThe 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:

One move that works and two that throwPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 7 to 14 make tryMove(). It tries one move. It prints moved, 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.

Four moves with moveBefore(). Oolong to Featured, both on one page: it moves. Oolong into a box that is off the page: it throws. Oolong into an iframe's body, another document: it throws. A new span into Featured, never on the page yet: it throws.oolongfeaturedmovesboth on one pageoolonga boxthrowsthe box is off the pageoolongframe's bodythrowsanother documentnew spanfeaturedthrowsnever on the page yet
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.
Real-life analogySliding only works along one counter

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() or append()

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:

A move() helper with a fallbackPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 NotFoundError is a real bug, and insertBefore() 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 prints insertBefore.

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?

Does moveBefore() move it, or throw?
  • featured.moveBefore(oolong, null), with both on the page
  • featured.moveBefore(shelf.firstChild, null), where the first child is text
  • box.moveBefore(green, null), where green is already inside the box, and the box isn't on the page
  • featured.moveBefore(document.createElement("span"), null)
  • box.moveBefore(oolong, null), for a box made with createElement()
  • template.content.moveBefore(oolong, null)
  • frame.contentDocument.body.moveBefore(oolong, null)
Try it yourself
0 of 7 correct

Sort each call by what Chrome does with it.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

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:

Playground: what should connectedMoveCallback() do?
A badge that says which shelf it's onPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
It stops and starts again

Without the method, moveBefore() runs disconnectedCallback(), then connectedCallback(). The badge stops and starts again, as if it had left the page.

The page stays the same. Only tea-badge.js changes: open its tab to compare. Each choice runs in a fresh 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's data-name attribute.
  • 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-label only 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-timer has 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.
Real-life analogyA guest who changes tables

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>'s content belongs 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.

Real-life analogyA library book that moves to another branch

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 oldDocument and newDocument arguments

Ravi keeps a spare badge in a <template>, like a storeroom. Watch what runs:

A badge visits the template's storeroomPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 8 to 10 of tea-badge.js, the second tab, are adoptedCallback(). 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, then adoptedCallback, 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, then connectedCallback.

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:

A badge moves into a receipt documentPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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, and connectedCallback.
  • Line 8 prints In the receipt: Oolong. Line 9 prints The receipt has a window: false.
Moving the Oolong badge from the page into the receipt document with receipt.body.append(badge). Three callbacks run in order: first disconnectedCallback, as it leaves the page; second adoptedCallback, as it changes documents; third connectedCallback, as it joins the receipt.pageOolongreceiptOolongreceipt.body.append(badge)disconnectedCallback()1. leaves the pageadoptedCallback()2. changes documentsconnectedCallback()3. joins the receipt
A move into another document runs three callbacks. 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:

A badge moves into an iframe's pageHTML
<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:

Two listeners, on two documentsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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, so this.ownerDocument is 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.

Real-life analogyA waiter on loan to the café next door

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:

A copy with importNode(), the real badge with adoptNode()Pop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 defined tea-badge, so the copy is a plain element.
  • Line 10 moves the badge itself. It prints disconnectedCallback and adoptedCallback, into this page: false. No connectedCallback: an adopted element has no parent yet.
  • Line 11 prints adoptNode() gave back the badge: true. Line 12 prints Badges on the page: 0.

Here are the three ways side by side. Read each row across:

Three ways into another document
What the code doesWhat 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:

The tea kit's timer, moved every wayPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 with moveBefore().
  • Line 23 serves the tea. It removes the timer for good.

Now open the tea-kit/tea-timer.js tab:

  • Line 2 starts #controller at null.
  • 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 isConnected after 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(), so moveBefore() 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 to insertBefore().
  • 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, as append() does. And a custom element without connectedMoveCallback() still stops and starts.
  • "moveBefore() works wherever append() 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, document is the element's document." No. It's the page where the class was written. Use this.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.

Exercise 1 · Warm-upCount the adoptions

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>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upWhich moves work?

    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>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeKeep typing after the move

      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>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeWrite the move() helper

        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>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeStart the brew only once

          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>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeA component in a document with no window

            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>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask two things: did the element leave its tree, and did it change documents?

              The moving and adopting quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does append() do with an element that's already on the page?

                Choose an answer to see the explanation.

              2. Question 2 of 8Which of these does moveBefore() keep?

                Choose an answer to see the explanation.

              3. Question 3 of 8What happens when you call featured.moveBefore(document.createElement("span"), null)?

                Choose an answer to see the explanation.

              4. Question 4 of 8This page uses the adoption examples' tea-badge.js. What does it print after connectedCallback?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              5. Question 5 of 8What does this page print after Moving?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <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.

              6. Question 6 of 8When does the browser call adoptedCallback()?

                Choose an answer to see the explanation.

              7. Question 7 of 8A component calls document.addEventListener() in connectedCallback(). Then it's moved into an iframe. Which document does that listener hear?

                Choose an answer to see the explanation.

              8. Question 8 of 8What should a timer's connectedMoveCallback() do?

                Choose an answer to see the explanation.

              Key takeaways

              • append() and insertBefore() 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 a HierarchyRequestError. Fall back to insertBefore(), 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, between disconnectedCallback() and connectedCallback().
              • Use this.ownerDocument, not document, and check defaultView before 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:

              Coming next: The custom element lifecycle in order. Step through every callback in the order the browser calls it.

              CompleteFrontend Clear concepts. Working examples.