completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Working with children

Read a web component's children as data, watch them with a MutationObserver, avoid render loops in light DOM components, and let children announce themselves.

By the end, you can
  • 01
    Read children as inputRead the elements a page puts inside your component, the way <select> reads its options, with children and :scope >.
  • 02
    Keep up when children changeWatch your own children with a MutationObserver, choose its options, read its batched records, and stop it when the element leaves.
  • 03
    Render without loops or lost childrenKeep the page's children, write into an element you own, and stop your own writes from waking your own observer.

How does a web component read its children?

Asha is writing the menu page for Leaf and Kettle. She types each tea straight into the HTML, as a <tea-item> with its price. Ravi's <tea-menu> tag goes around them. The menu should say how many teas there are, and which one is the cheapest.

But Asha never hands Ravi's class a list. No attribute holds the teas. They are just there, inside the tag. So how does the menu find out what is on it?

A web component reads its children the way a <select> reads its <option> elements. Its class looks at the elements inside it, with this.children or this.querySelectorAll(":scope > tea-item"), and treats them as input. Children can change later, so it also watches them with a MutationObserver.

The elements inside a tag are its children. You already use a tag that reads its children. A <select> has no list of its own. It makes its dropdown from the options you put inside it:

A select reads the options inside itPop out in the code editor (opens in a new tab)HTML
<select>  <option>Green tea</option>  <option>Black tea</option></select> <script>  const select = document.querySelector("select");  console.log(select.length, "options");  select.insertAdjacentHTML("beforeend", "<option>Mint tea</option>");  console.log(select.length, "options");</script>
ResultLoading…
  • Lines 1 to 4 are a select with two options.
  • Line 8 prints how many options it has: 2 options.
  • Line 9 adds a third option inside it. Line 10 prints 3 options.

The HTML Standard calls these the select's list of options. The select reads them, and keeps up when one is added. Open the dropdown in the result: Mint tea is there.

Ravi's menu can work the same way. Here it reads each tea when it joins the page:

A tea menu reads the teas inside itPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="5">Mint tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu> <script>  class TeaMenu extends HTMLElement {    connectedCallback() {      for (const tea of this.children) {        console.log(tea.textContent, "costs", tea.getAttribute("price"));      }    }  }  customElements.define("tea-menu", TeaMenu);</script>
ResultLoading…
  • Lines 1 to 5 are Asha's HTML: a menu with three teas inside.
  • Line 10 loops over this.children, the elements inside the menu.
  • Line 11 reads each tea's words with textContent, and its price with getAttribute("price").
  • It prints Green tea costs 4, Mint tea costs 5, and Black tea costs 3.

The script comes after the menu, so the teas are already there when connectedCallback() runs. That isn't always true. Lesson 3.6, The custom element lifecycle in order, showed that a class loaded before the HTML runs connectedCallback() before any child is read, and how to wait for them. And never read children in the constructor. The HTML Standard says not to, as What the constructor may do explained.

Two elements that read what's inside them. On the left, a select element with two option children, Green tea and Black tea, and an arrow going up from each option to the select. On the right, a tea-menu with three tea-item children, Green tea, Mint tea, and Black tea, and an arrow going up from each one to the menu.a built-in element<select>Green teaBlack teaits option childrenyour custom element<tea-menu>Green teaMint teaBlack teaits tea-item children
A <select> builds its dropdown from the <option> elements inside it. Your <tea-menu> can do the same with its <tea-item> children. They are its input.

There's a bonus to keeping the teas in the HTML. If the script never loads, the page still shows Green tea, Mint tea, and Black tea. The HTML makes sense on its own, like a select full of options.

Real-life analogyA cashier reads your basket

At the shop's till, you don't tell the cashier what you bought. You put the basket down. The cashier takes out each thing, reads its price tag, and prints the receipt. The basket is the list.

In real life: The basket
In JavaScript: The <tea-menu> element
In real life: The things you put in it
In JavaScript: Its <tea-item> children
In real life: The price tag on each one
In JavaScript: Each tea's price attribute
In real life: The receipt
In JavaScript: What the menu works out: how many, and the cheapest
The main idea

The elements inside your tag are its input. Read them in connectedCallback(), keep to your own children, and watch them for changes. If your component draws into its own children, make sure its own writes don't wake its own observer.

What is the difference between children and childNodes?

The page is a tree of nodes. A node is any one thing in that tree: an element, a run of text, or a comment. The DOM tree lesson showed that even the spaces and line breaks between tags are text nodes.

So an element has two lists of what's inside it:

  • children holds only the elements.
  • childNodes holds every node: elements, text, and comments.

Here is a menu with a comment in it:

children and childNodes in one menuPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <!-- Hot teas -->  <tea-item price="4">Green tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu> <script>  class TeaMenu extends HTMLElement {    connectedCallback() {      console.log("children:", this.children.length);      console.log("childNodes:", this.childNodes.length);      console.log([...this.childNodes].map((node) => node.nodeName).join(" "));    }  }  customElements.define("tea-menu", TeaMenu);</script>
ResultLoading…
  • Line 2 is an HTML comment. It shows nothing on the page.
  • Line 10 prints children: 2. Only the two teas are elements.
  • Line 11 prints childNodes: 7.
  • Line 12 prints the name of each node: #text #comment #text TEA-ITEM #text TEA-ITEM #text.

Each #text is the line break and spaces between two tags. Loop over childNodes, and your menu trips on four blank texts and a comment. Loop over children, and it gets just the teas.

Inside each tea, read the words with textContent. It joins all the text inside, so it's the tea's name. Read the price with getAttribute(), which gives back a string, like "4". Lesson 5.2, Boolean, number, and enum attributes, turned strings like that into numbers.

Read attributes, not properties, from a child. A child may not have its class yet, as lesson 3.6 showed. Its attributes are there from the start.

Why it matters: children gives you the input, and childNodes gives you the input plus the gaps. The DOM navigation lesson has the full set of these properties.

How do you select only a component's own children?

Sometimes you want only some children, like the teas but not a heading. Then you search with a CSS selector. this.querySelectorAll() searches inside your element only. document.querySelectorAll() searches the whole page. The Astro docs point out why this matters: with two menus on a page, each one reads only its own teas.

But "inside" means all the way down. Here a menu holds another menu:

A menu inside a menuPop out in the code editor (opens in a new tab)HTML
<tea-menu name="Hot teas">  <tea-item price="4">Green tea</tea-item>  <tea-item price="5">Mint tea</tea-item>  <tea-menu name="Iced teas">    <tea-item price="6">Iced lemon tea</tea-item>  </tea-menu></tea-menu> <script>  class TeaMenu extends HTMLElement {    connectedCallback() {      const all = this.querySelectorAll("tea-item").length;      const own = this.querySelectorAll(":scope > tea-item").length;      console.log(`${this.getAttribute("name")}: ${all} inside, ${own} its own`);    }  }  customElements.define("tea-menu", TeaMenu);</script>
ResultLoading…
  • Lines 1 to 7 are the Hot teas menu. Its last child, on lines 4 to 6, is a second menu, Iced teas.
  • Line 12 counts every tea-item inside the menu, at any depth.
  • Line 13 counts with :scope > tea-item.
  • Line 14 prints for each menu: Hot teas: 3 inside, 2 its own, then Iced teas: 1 inside, 1 its own.
A menu inside a menu. At the top, the Hot teas menu. Arrows lead down to its three children: Green tea, Mint tea, and the Iced teas menu. One more arrow leads from the Iced teas menu down to Iced lemon tea, a grandchild of Hot teas. Green tea and Mint tea are marked as the menu's own teas.Hot teasGreen teaMint teaIced teasthe menu's own teasIced lemon teaa grandchild of Hot teas
Inside Hot teas, querySelectorAll("tea-item") finds all 3 teas, even Iced lemon tea, which belongs to the inner menu. :scope > tea-item finds only the 2 that are Hot teas' own children.

Read the selector in two parts. :scope means the element you called it on, here the menu. The > means "a direct child of". So :scope > tea-item is "a tea whose parent is this menu". It skips Iced lemon tea, which is a grandchild. MDN has the details.

Why it matters: menus inside menus, lists inside lists, and tabs inside tabs are common. Without :scope >, the outer one counts the inner one's teas as its own.

How do you react when a web component's children change?

Reading once isn't enough. After the page loads, a script can add a tea, change a price, or fix a name. The menu has to notice. Lesson 3.6 waited for the first children to arrive, and Loading definitions on demand watched the whole page for new tags. Here the menu keeps up with its own children, for as long as it's on the page.

The tool is a MutationObserver: an object the browser calls when part of the page changes. The Observers lesson covers it in full. A component watches one element, itself, and says which kinds of change it cares about. Those choices are its options. They are like telling a guard which doors to watch.

Try it. The page has three buttons, and each one makes a different kind of change:

Playground: which changes does the menu see?
A menu that watches its own childrenPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu><button>Add Oolong at 2</button><button>Raise Black tea to 6</button><button>Rename Black tea</button> <script src="tea-menu.js"></script><script>  const menu = document.querySelector("tea-menu");  const black = menu.lastElementChild;  const [add, raise, rename] = document.querySelectorAll("button");  add.onclick = () => menu.insertAdjacentHTML("beforeend", '<tea-item price="2">Oolong</tea-item>');  raise.onclick = () => black.setAttribute("price", "6");  rename.onclick = () => (black.firstChild.data = "Assam tea");</script>
ResultLoading…
Try it yourself
It sees every change

Press each button. The menu prints its teas again every time: a tea added, a price raised, a name edited. subtree lets it see inside each tea.

The options object in the tea-menu.js tab changes with your choice. Press the three buttons in the result and watch the console. Run again starts the page over.

Start in the tea-menu.js tab, with all four options on:

  • Line 2 makes one observer for each menu, as a private field. Its job is to call #read().
  • Line 5 reads the teas once, when the menu joins the page.
  • Line 6 starts watching this, the menu itself. Lines 7 to 10 are the options.
  • Line 15 stops watching when the menu leaves the page.
  • Line 19 finds the menu's own teas. Line 21 prints each name and price.

Now the page:

  • Line 14 adds Oolong at 2. The console prints Green tea 4, Black tea 3, Oolong 2.
  • Line 15 raises Black tea's price to 6. The console prints Green tea 4, Black tea 6, Oolong 2.
  • Line 16 changes the words inside Black tea's text node. The console prints Green tea 4, Assam tea 6, Oolong 2.

Now switch the choices, and press the buttons again. With fewer options, the menu misses changes, and its list goes out of date. Here is what each option adds:

Which option catches which change
OptionWhat it reportsWhich button needs it
childList: trueChildren added to or removed from the watched element.Add Oolong at 2.
subtree: trueChanges anywhere inside the element, not only on the element itself. The other options need it to reach inside a tea.Raise and Rename, together with the options below.
attributeFilter: ["price"]Changes to the price attribute only. Listing names also turns attributes on.Raise Black tea to 6.
characterData: trueEdits to the words inside a text node, like node.data = "Assam tea".Rename Black tea.

Two details catch people out. First, attributeFilter alone turns on attributes. The DOM Standard's observe() steps do that for you. Second, setting textContent doesn't edit a text node. It swaps the old text node for a new one. That's a childList change, not a characterData one.

And remember line 15 of tea-menu.js. Chrome's guide to custom elements says to remove observers in disconnectedCallback(), or they leak. The course took a menu off the page without its disconnectedCallback(), then added a tea to it. Its observer still called back. Lesson 3.3 covers cleaning up in disconnectedCallback().

Why it matters: an observer reports only what you ask for. Ask for too little, and the menu shows old prices. Ask for too much, and it wakes up for changes it doesn't need.

Why does a MutationObserver callback get several records at once?

The callback gets a list of records. A record is a small object that describes one change: its type, the node it happened to, and what was added or removed. One click can make many changes. Watch what arrives:

Three changes in one clickPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="5">Mint tea</tea-item></tea-menu><button>Change three things</button> <script>  const menu = document.querySelector("tea-menu");  const [green, mint] = menu.children;  const options = { childList: true, subtree: true, attributeFilter: ["price"], characterData: true };  new MutationObserver((records) => {    console.log(records.length, "records:", records.map((record) => record.type).join(", "));  }).observe(menu, options);   document.querySelector("button").onclick = () => {    menu.insertAdjacentHTML("beforeend", '<tea-item price="3">Black tea</tea-item>');    mint.setAttribute("price", "6");    green.firstChild.data = "Sencha";    console.log("Three changes made");  };</script>
ResultLoading…
  • Lines 11 to 13 make an observer that prints how many records it got, and their types.
  • Lines 16 to 18 make three changes: add a tea, change a price, and change a name.
  • Line 19 prints Three changes made.

Press the button. The console prints Three changes made first. Then it prints 3 records: childList, attributes, characterData. The callback ran once, after the click handler was done. The records came in the order the changes happened.

The DOM Standard spells this out. Each change adds a record to the observer's list. The first one also queues a microtask: a small job that runs as soon as the current code finishes. When it runs, the observer gets the whole list in one call. The microtasks lesson covers that queue.

Real-life analogyThe post comes in one bundle

Letters for the tea shop arrive all morning. The postman doesn't knock once for each one. He collects them in his bag, then knocks once and hands over the bundle. Ravi reads them in order.

In real life: Each letter
In JavaScript: One record
In real life: The bag the letters wait in
In JavaScript: The observer's list of records
In real life: One knock with the whole bundle
In JavaScript: One call to the callback with every record
In real life: Reading them in the order they were sent
In JavaScript: Records in the order the changes happened

Reading everything again, or patching

You can use the records two ways. You can ignore what they say, and read all your children again. That's what the menu in the playground does. Or you can patch: read only what the records say changed.

Reading only the teas that were addedPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item>Green tea</tea-item></tea-menu><button>Add two teas</button> <script>  const menu = document.querySelector("tea-menu");  new MutationObserver((records) => {    for (const record of records) {      for (const node of record.addedNodes) {        if (node.localName === "tea-item") console.log("New tea:", node.textContent);      }    }  }).observe(menu, { childList: true });   document.querySelector("button").onclick = () => {    menu.insertAdjacentHTML("beforeend", "<tea-item>Oolong</tea-item><tea-item>Chai</tea-item>");  };</script>
ResultLoading…
  • Line 9 goes through each record. Line 10 goes through its addedNodes, the nodes it added.
  • Line 11 skips anything that isn't a tea, like a text node, and prints the rest.
  • Line 17 adds two teas in one go. They arrive in one record. The console prints New tea: Oolong and New tea: Chai.

Here is how the two ways compare:

Reading everything again, or patching from the records
What you want to knowRead everything againPatch from the records
How much code is it?A little. One function runs at connect and on every change.More. You handle each kind of record, and added and removed nodes.
Can it get out of step with the page?No. It always reads what's there now.Yes, if it misses a kind of record.
When is it worth it?For most components. Menus, lists, and tabs have only a few children.For long lists, where reading everything again is slow.

Why it matters: start by reading everything again. It's short, and it can't drift from what's on the page. Patch only when a list is long enough to be slow.

Why does a component's MutationObserver run in a loop?

So far, the menus only printed to the console. A real menu shows its summary on the page. Where can it draw it?

A component can have a shadow root: a private tree of its own. Stage 3, Shadow DOM, templates, and slots, builds them. Without one, it has just one place to draw: among its own children, next to the page's teas. That's where two traps wait.

Writing over the page's children

The first trap is the easiest to fall into. This menu draws with innerHTML:

A menu that writes over its teasPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="5">Mint tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu><button>Move the menu</button> <script>  class TeaMenu extends HTMLElement {    connectedCallback() {      const teas = this.children.length;      this.innerHTML = `<p>${teas} teas on the menu</p>`;    }  }  customElements.define("tea-menu", TeaMenu);   const menu = document.querySelector("tea-menu");  document.querySelector("button").onclick = () => document.body.append(menu);</script>
ResultLoading…
  • Line 11 counts the menu's children: 3.
  • Line 12 sets innerHTML. That throws away everything inside the menu, and puts one <p> there.
  • Line 18 moves the menu to the end of the page when you press the button.

The result shows 3 teas on the menu, and no teas. Asha's three teas are gone. Now press Move the menu. It says 1 teas on the menu. A move runs connectedCallback() again, as lesson 3.3 showed. This time, the only child is the <p>. Chris Ferdinandi's guide warns about the same thing: setup that adds to the element runs again on every move. Exercise 5 asks you to fix this menu.

Waking your own observer

The second trap is subtler. This menu keeps the teas. It creates its own <p> once, puts it first, and writes the count into it. It also watches its children:

A menu whose own writes wake its observerPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item>Green tea</tea-item>  <tea-item>Black tea</tea-item></tea-menu><button>Add Oolong</button> <script src="tea-menu.js"></script><script>  const menu = document.querySelector("tea-menu");  document.querySelector("button").onclick = () => {    menu.insertAdjacentHTML("beforeend", "<tea-item>Oolong</tea-item>");  };</script>
ResultLoading…
  • In the tea-menu.js tab, line 2 creates the summary <p>, once for each menu.
  • Line 7 puts it first with prepend(), which adds a node before all the other children.
  • Line 8 draws the summary. Line 9 starts watching.
  • Line 14 prints the number of each render. Line 16 writes the count into the <p>.
  • Line 18 is a safety stop. It gives up after five renders.

The console prints Render 1. Press Add Oolong once. It prints Render 2, Render 3, Render 4, and Render 5, then stops.

Here is why. The <p> is one of the menu's children, and the observer watches with subtree. So line 16 is a change the menu is watching. Each render writes, the write makes a record, and the record calls the render again.

A loop of four steps. The render writes the summary. The p element's text changes. A record is queued. The callback runs, which calls the render again, back at the first step. In the middle: and again, and again.#render() writesthe <p> text changesa record is queuedthe callback runsand again, and again
Without a guard, the menu's own write is a change it's watching. Each render queues one more record, so the callback runs again. Nothing in the loop ever stops it.

Without line 18 of tea-menu.js, it would never stop. The course raised the stop to 1,000 renders, and Chrome reached all 1,000 after one click. The HTML Standard runs microtasks until none are left. While this loop runs, there is always one more. So the page can't draw or answer a click, and it freezes.

Real-life analogyA shelf that never stays tidy

A new helper at the shop gets one rule: tidy the shelf whenever something on it moves. A customer moves a tin, so she tidies. Tidying moves tins. So she tidies again, and again. She never gets to serve anyone.

In real life: The shelf
In JavaScript: The menu's children
In real life: Tidying it
In JavaScript: #render() writing the summary
In real life: "Tidy whenever something moves"
In JavaScript: A MutationObserver with subtree
In real life: Her own tidying moving things
In JavaScript: The summary's change making a record

There are several ways to stop the loop. Some work, and some only look like they should. Try each one:

Playground: five ways to stop the loop
A menu that writes its summary among its childrenPop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item>Green tea</tea-item>  <tea-item>Black tea</tea-item></tea-menu><button>Add Oolong</button> <script src="tea-menu.js"></script><script>  const menu = document.querySelector("tea-menu");  document.querySelector("button").onclick = () => {    menu.insertAdjacentHTML("beforeend", "<tea-item>Oolong</tea-item>");  };</script>
ResultLoading…
Try it yourself
It still loops

It still loops until the safety stop: Render 1 to Render 5. The flag is back to false before the records arrive, because the observer calls back later, in a microtask.

Only the tea-menu.js tab changes with your choice. Press Add Oolong once and count the Render lines in the console. Run again starts the page over.

Three of them work. Each one keeps the menu's own writes away from its callback:

  • Ignore its own records. The callback checks where each record happened. If every one is inside the menu's <p>, it returns. contains() tells whether a node is inside another node, or is that node.
  • Take its own records. takeRecords() hands back the waiting records and leaves the list empty, as MDN describes. So the callback never gets them.
  • Stop watching while it writes. disconnect() stops the observer, and observe() starts it again after the write.

The flag fails because of the timing from the last section. The callback runs later, in a microtask. By then the flag is false again. And "only write new text" ends the loop, but every change still renders twice.

Why it matters: give the component one element it owns, and make sure its writes there can't wake it. The tea kit uses the first fix: its callback skips any batch that's only about its own <p>.

What is a light DOM web component?

An element's ordinary children are called its light DOM. They are the ones the page wrote. Anyone can see them, search them, and style them. A light DOM web component is one that uses only those. It has no shadow root.

Every menu in this lesson so far is one. They work best when they leave the page's children in place, and add to them. Here the menu marks the cheapest tea in a plain list:

A menu that marks the cheapest tea in placePop out in the code editor (opens in a new tab)HTML
<style>  [data-cheapest] { font-weight: bold; }</style> <tea-menu>  <ul>    <li data-price="4">Green tea</li>    <li data-price="3">Black tea</li>    <li data-price="5">Mint tea</li>  </ul></tea-menu> <script>  class TeaMenu extends HTMLElement {    connectedCallback() {      const items = [...this.querySelectorAll(":scope > ul > li")];      const price = (item) => Number(item.dataset.price);      const cheapest = items.reduce((low, item) => (price(item) < price(low) ? item : low));      for (const item of items) item.toggleAttribute("data-cheapest", item === cheapest);    }  }  customElements.define("tea-menu", TeaMenu);</script>
ResultLoading…
  • Lines 5 to 11 are plain HTML: a list of teas, each with a price.
  • Line 16 finds the list items with :scope > ul > li.
  • Line 17 reads a price with dataset, which gives the data- attributes as properties.
  • Line 18 finds the cheapest tea.
  • Line 19 adds data-cheapest to that tea, and removes it from the rest.
  • Line 2, in the page's CSS, makes the marked tea bold.

Black tea shows in bold. If the script never loads, the list is still a list. The page owns the HTML and the style. The component only adds a mark. Running it again gives the same result, so a move can't break it. The next lesson, HTML web components, builds whole components this way.

Real-life analogyA frame around your own photo

A frame shop puts a frame around your photo. It doesn't paint a new picture. It can tuck a small card with the date into the corner. Everyone in the room still sees your photo, in the room's own light.

In real life: Your photo
In JavaScript: The page's children
In real life: The frame
In JavaScript: The light DOM component
In real life: The little card with the date
In JavaScript: Something the component adds, like the summary
In real life: The room's light falling on it all
In JavaScript: The page's CSS

That light falls on everything. The page's CSS reaches the page's children, and it also reaches whatever the component adds:

The page's CSS reaches the menu's own pPop out in the code editor (opens in a new tab)HTML
<style>  tea-item { display: block; color: green; }  p { color: red; }</style> <tea-menu>  <tea-item>Green tea</tea-item>  <tea-item>Black tea</tea-item></tea-menu> <script>  class TeaMenu extends HTMLElement {    #summary = document.createElement("p");     connectedCallback() {      const teas = this.querySelectorAll(":scope > tea-item").length;      this.#summary.textContent = `${teas} teas`;      this.prepend(this.#summary);    }  }  customElements.define("tea-menu", TeaMenu);</script>
ResultLoading…
  • Line 2 makes each tea a block, and green. Line 3 makes every <p> on the page red.
  • Line 13 creates the menu's summary <p>. Lines 16 to 18 write the count, and put it first.

The teas are green. The summary, 2 teas, is red. The menu didn't ask for that, but its <p> is just another element on the page. In lesson 1.1, What are web components?, the same p rule couldn't reach a <p> inside a shadow root.

Some people want exactly this. Heydon Pickering of Every Layout styles his layout components and their children from the page's own stylesheet, with no shadow DOM at all. When a component's insides must not change with the page, that's what stage 3's shadow roots and slots are for.

Why it matters: a light DOM component shares the page. Keep the page's children, add as little as you can, and expect the page's CSS on everything you add.

How can child elements tell their parent they exist?

So far, the menu has done all the looking. When the children are components too, they can tell the menu themselves. Each tea sends an event when it joins a page. The event bubbles up, so the menu above it hears it. Lesson 5.3 covered how to dispatch an event that bubbles.

Teas that tell the menu they're herePop out in the code editor (opens in a new tab)HTML
<tea-menu>  <tea-item>Green tea</tea-item>  <tea-item>Mint tea</tea-item></tea-menu><button>Add Oolong</button><button>Remove Green tea</button> <script src="tea-menu.js"></script><script src="tea-item.js"></script><script>  const menu = document.querySelector("tea-menu");  const [add, remove] = document.querySelectorAll("button");  add.onclick = () => menu.insertAdjacentHTML("beforeend", "<tea-item>Oolong</tea-item>");  remove.onclick = () => menu.querySelector("tea-item").remove();</script>
ResultLoading…
  • In the tea-item.js tab, line 3 sends tea-item-connected when a tea joins the page. bubbles: true lets it travel up through the tea's parents.
  • Line 7 sends tea-item-disconnected when a tea leaves.
  • In the tea-menu.js tab, lines 4 to 9 listen for both. The constructor may add listeners, as lesson 3.2 showed.
  • On the page, line 8 loads the menu's class first, and line 9 the teas' class.

The console prints Menu heard: Green tea and Menu heard: Mint tea. Press Add Oolong, and it prints Menu heard: Oolong. A new tea told the menu, with no observer at all.

Now press Remove Green tea. Nothing prints. By the time disconnectedCallback() runs, the tea is out of the menu. Its event goes up from where it is now, and the menu isn't there.

Teas telling the menu they're here. Mint tea and Oolong each send tea-item-connected up to the tea-menu above them. A third tea, Green tea, was removed. Its event goes up from where it is now, and the menu never hears it.<tea-menu>Mint teaOolongtea-item-connected bubbles upno one hears itGreen tea, removedsent after it left
Each tea announces itself with a bubbling event, and the menu above it listens. Green tea announces it's leaving too late: it's no longer inside the menu.
Real-life analogyGuests check in at the front desk

At a hotel, each guest stops at the front desk when they arrive. The desk doesn't walk the halls to count people. But a guest who leaves by the back door never checks out. The desk still thinks they're there.

In real life: A guest arriving
In JavaScript: A tea joining the page
In real life: Checking in at the desk
In JavaScript: Dispatching tea-item-connected
In real life: The desk
In JavaScript: The menu's listener
In real life: A guest who left without a word
In JavaScript: A tea removed from the menu

Load order matters too. The course swapped lines 8 and 9, so the teas' class loaded first. The two teas announced themselves before the menu had a listener, and the menu heard only Oolong. Justin Fagnani of the Lit team uses child events, and wrote about it in issue 809. He has each child wait for its parent's class with customElements.whenDefined() before it sends its event. Exercise 6 fixes it a simpler way: the menu also reads the teas already there when it connects.

Here is how the two ways compare:

The parent looks, or the child tells
What you want to knowThe parent looks (a query and an observer)The child tells (an event)
Does it work with plain HTML children, like <li>?Yes. It reads any element.No. Only a custom element's class can dispatch.
Does it notice a child leaving?Yes. A childList record lists the removed nodes.No. The child has left before its event is sent.
Does it notice a price or a name changing?Yes, with subtree, attributeFilter, and characterData.Only if the child sends another event for each change.
Does the order the classes load in matter?No. It reads whatever is there when it connects.Yes. A child that connects before the parent's class runs is missed.
Can it carry data?It reads attributes and text.Yes. The event can carry any data, as lesson 5.3 showed.

There is still no callback for "my children changed". Issue 809 asked for one in 2019. Ryosuke Niwa of Apple compared it to attributeChangedCallback(): a shortcut for something an observer can already do. It is still open.

Why it matters: events suit children that are components and need to send data up. Looking suits everything else, including plain HTML and children that leave. Many components do both.

Adding a tea menu to the tea kit

The tea kit gets two new files in this lesson:

  • tea-kit/tea-item.js is one tea. Its text is the name, and its price property reflects the price attribute.
  • tea-kit/tea-menu.js reads its teas, and keeps a summary in a <p> it owns.
The tea kit's menu on a pagePop out in the code editor (opens in a new tab)HTML
<style>  tea-item { display: block; }</style> <tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="5">Mint tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu><button>Add Oolong at 2</button><button>Raise Black tea to 6</button> <script type="module">  import "./tea-kit/index.js";   const menu = document.querySelector("tea-menu");  const black = menu.lastElementChild;  const [add, raise] = document.querySelectorAll("button");  add.onclick = () => menu.insertAdjacentHTML("beforeend", '<tea-item price="2">Oolong</tea-item>');  raise.onclick = () => (black.price = 6);</script>
ResultLoading…
  • Line 2 makes each tea a block. That's the page's CSS, as in the last section.
  • Lines 5 to 9 are three teas in a menu, in plain HTML.
  • Line 14 loads the whole kit, which now defines tea-item and tea-menu.
  • Line 19 adds Oolong at 2. Line 20 sets Black tea's price property to 6.

The menu shows 3 teas. Cheapest: Black tea, 3. Press Add Oolong at 2, and it shows 4 teas. Cheapest: Oolong, 2. Run it again and press Raise Black tea to 6 instead. It shows 3 teas. Cheapest: Green tea, 4.

Now open the tea-kit/tea-menu.js tab. It puts the whole lesson together:

  • Line 9 creates the summary <p> once. A move can't make a second one.
  • Line 11 skips a batch when every record is about the summary. That's the fix from the loop playground.
  • Lines 16 and 17 put the summary first and draw it.
  • Lines 18 to 23 watch for teas added or removed, price changes, and edited names.
  • Line 27 stops watching when the menu leaves the page.
  • Line 31 reads only the menu's own teas, with :scope > tea-item.
  • Lines 32 and 33 read each name and price from the text and the attribute. toFloat() comes from lesson 5.2.
  • Line 40 writes the summary.

In the tea-kit/tea-item.js tab, the price getter reads the attribute, and the setter writes it. connectedCallback() runs the upgrade-property pattern from Properties set before the upgrade. The kit's custom-elements.json now lists both tags, as Designing a component API asked of every public part.

Common mix-ups

  • "A component's children are always there in connectedCallback()." No. With the class loaded first, the parser runs it before any child, as lesson 3.6 showed. And children can change later.
  • "childNodes is a list of the child elements." No. It holds every node, with comments and the blank text between tags. children holds only elements.
  • "this.querySelectorAll("tea-item") finds only my own teas." No. It finds every tea inside, at any depth. Use :scope > tea-item for direct children.
  • "The observer calls back once for each change." No. It collects the records, and calls back once with all of them, after the current code finishes.
  • "A flag around my own writes keeps my observer from seeing them." No. The records arrive later, in a microtask. By then the flag is off again.
  • "An observer stops when its element leaves the page." No. It keeps calling back until you call disconnect(). Do it in disconnectedCallback().
  • "Without shadow DOM, the page's CSS can't touch what my component adds." No. In the light DOM, the page's CSS reaches everything, including your summary.
  • "A child can tell its old parent that it left." No. When disconnectedCallback() runs, the child is already out, so its event can't reach the parent.

Practice exercises

Answer first, then use the hints. The results run live, so you can check yourself.

Exercise 1 · Warm-upNo spaces between the tags

What does line 6 print?

<tea-menu><tea-item>Green tea</tea-item><!-- new --><tea-item>Mint tea</tea-item></tea-menu>

<script>
  class TeaMenu extends HTMLElement {
    connectedCallback() {
      console.log(this.children.length, this.childNodes.length);
    }
  }
  customElements.define("tea-menu", TeaMenu);
</script>

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

    Exercise 2 · Warm-upA tea wrapped in a div

    What does line 11 print?

    <tea-menu>
      <tea-item>Green tea</tea-item>
      <div><tea-item>Mint tea</tea-item></div>
    </tea-menu>
    
    <script>
      class TeaMenu extends HTMLElement {
        connectedCallback() {
          const all = this.querySelectorAll("tea-item").length;
          const own = this.querySelectorAll(":scope > tea-item").length;
          console.log(all, own);
        }
      }
      customElements.define("tea-menu", TeaMenu);
    </script>

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

      Exercise 3 · PracticeA menu that misses sold-out teas

      Press the button. Black tea is now sold out, but the menu prints nothing. Fix the observer. What does the console print after you press the button?

      <tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu><button>Black tea is sold out</button> <script>  class TeaMenu extends HTMLElement {    #observer = new MutationObserver(() => this.#read());     connectedCallback() {      this.#read();      this.#observer.observe(this, {        childList: true,        subtree: true,        attributeFilter: ["price"],      });    }     #read() {      const teas = [...this.querySelectorAll(":scope > tea-item:not([sold-out])")];      console.log(teas.map((tea) => tea.textContent).join(", "));    }  }  customElements.define("tea-menu", TeaMenu);   const black = document.querySelector("tea-menu").lastElementChild;  document.querySelector("button").onclick = () => black.toggleAttribute("sold-out", true);</script>
      ResultLoading…

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

        Exercise 4 · PracticeThree teas in a loop

        Press the button once. What does the console print?

        <tea-menu></tea-menu>
        <button>Add three teas</button>
        
        <script>
          const menu = document.querySelector("tea-menu");
          new MutationObserver((records) => {
            console.log("Callback with", records.length, "records");
          }).observe(menu, { childList: true });
        
          document.querySelector("button").onclick = () => {
            for (const name of ["Oolong", "Chai", "Sencha"]) {
              menu.insertAdjacentHTML("beforeend", `<tea-item>${name}</tea-item>`);
            }
          };
        </script>

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

          Exercise 5 · ChallengeKeep the teas, and the count

          This is the menu from the loop section. Fix it so the teas stay, and the count stays right after Move the menu. What does its first line say after a move?

          <tea-menu>  <tea-item price="4">Green tea</tea-item>  <tea-item price="5">Mint tea</tea-item>  <tea-item price="3">Black tea</tea-item></tea-menu><button>Move the menu</button> <script>  class TeaMenu extends HTMLElement {    connectedCallback() {      const teas = this.children.length;      this.innerHTML = `<p>${teas} teas on the menu</p>`;    }  }  customElements.define("tea-menu", TeaMenu);   const menu = document.querySelector("tea-menu");  document.querySelector("button").onclick = () => document.body.append(menu);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeA menu that missed its first teas

            The console stays empty until you press Add Oolong, and then it says Teas known: 1. Make the menu know all its teas. What does the console print after one press of Add Oolong?

            <tea-menu>  <tea-item>Green tea</tea-item>  <tea-item>Mint tea</tea-item></tea-menu><button>Add Oolong</button> <script src="tea-item.js"></script><script src="tea-menu.js"></script><script>  const menu = document.querySelector("tea-menu");  document.querySelector("button").onclick = () => {    menu.insertAdjacentHTML("beforeend", "<tea-item>Oolong</tea-item>");  };</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask which children the code can see, and when the observer hears about a change.

              The working with children quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Which property gives a component only the elements inside it, without text or comments?

                Choose an answer to see the explanation.

              2. Question 2 of 7What does this summary snippet print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const menu = document.createElement("tea-menu");
                menu.innerHTML = "<tea-item>Green tea</tea-item><tea-item>Black tea</tea-item>";
                menu.prepend(document.createElement("p"));
                console.log(menu.children.length, menu.querySelectorAll(":scope > tea-item").length);

                Choose an answer to see the explanation.

              3. Question 3 of 7A click handler adds a tea, raises a price, and renames a tea. How often does the menu's observer callback run?

                Choose an answer to see the explanation.

              4. Question 4 of 7A menu sets #rendering = true before writing its summary and false after. Why does it still loop?

                Choose an answer to see the explanation.

              5. Question 5 of 7The page's CSS says p { color: red; }. A light DOM menu adds a <p> with its summary. What color is the summary?

                Choose an answer to see the explanation.

              6. Question 6 of 7A tea dispatches a bubbling event from disconnectedCallback(). Does the menu it just left hear it?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which options let a menu see a tea's price attribute change?

                Choose an answer to see the explanation.

              Key takeaways

              • The elements inside your tag are its input, like a select's options. Read them in connectedCallback(), never the constructor.
              • children holds elements only. childNodes adds text and comments.
              • this.querySelectorAll() searches at every depth. :scope > keeps it to your own children.
              • A MutationObserver on this keeps up with changes. Choose childList, subtree, attributeFilter, and characterData for what you need.
              • The callback gets every record from one piece of code at once, in a microtask, in order.
              • Disconnect the observer in disconnectedCallback(), or it keeps calling back.
              • In the light DOM, never write over the page's children. Write into an element you own, and keep those writes from waking your observer.
              • A child component can announce itself with a bubbling event, but it can't announce leaving.

              Remember the one-liner.
              Your children are your input: read your own, watch them for changes, and never let your own writes wake your observer.

              Sources

              The facts on this page come from these standards, docs, and posts:

              Coming next: HTML web components. Wrap ordinary HTML in a custom element to add behavior, so it works before JavaScript loads.

              CompleteFrontend Clear concepts. Working examples.