Reacting to attributes
Learn how attributeChangedCallback and observedAttributes let a custom element react to attribute changes, including at upgrade and before connectedCallback.
- 01List the attributes you care aboutWrite
observedAttributes, and know thatdefine()reads it only once. - 02Read the callback's three argumentsSay what
name,oldValue, andnewValuehold, and when one of them isnull. - 03Handle the timing and the repeatsExpect the callback before
connectedCallback(), skip values that didn't change, and stop a setter loop.
What does attributeChangedCallback do?
Asha's online shop for Leaf and Kettle shows a price next to each tea. It uses the tea kit's tea-price from lesson 3.1. The tag <tea-price amount="4"> shows Price: 4.
Today the owner starts a sale, and oolong drops to 3. Asha's script sets the tag's amount attribute to 3. In DevTools, the tag now says amount="3". But the page still says Price: 4. Why didn't the price change? And how can a component notice that an attribute changed?
To react when an attribute changes, list its name in a static observedAttributes array on your class. Then write an attributeChangedCallback(name, oldValue, newValue) method. The browser calls that method each time a listed attribute is added, changed, or removed.
First, here is Asha's bug. The page loads the kit's first tea-price.js, in the second tab:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script type="module"> import "./tea-price.js"; const price = document.querySelector("tea-price"); price.setAttribute("amount", "3"); console.log("Attribute:", price.getAttribute("amount")); console.log("Text:", price.textContent);</script>- Line 4 loads the kit's price. Its class reads
amountonly inconnectedCallback(), when it joins the page. - Line 7 sets
amountto 3. - Line 8 prints
Attribute: 3. The attribute did change. - Line 9 prints
Text: Price: 4. The text didn't.
Nothing told the price about line 7. connectedCallback() runs when the element joins the page, as lesson 3.3 showed. Changing an attribute isn't joining. Here is a price that listens:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed from ${oldValue} to ${newValue}`); this.textContent = `Price: ${newValue}`; } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.setAttribute("amount", "3");</script>- Line 5 is the list. It names the attributes this class cares about. Here, that's just
amount. - Lines 7 to 10 are the callback. The browser passes in the name, the old value, and the new value.
- Line 8 prints those three. Line 9 writes the new price into the tag.
- Line 15 changes
amountto 3.
The console prints two lines. The first is amount changed from null to 4. But nothing had changed yet. So where did it come from? From line 12. The tag already had amount="4" when define() upgraded it, and the browser counts that as a change. Then line 15 prints amount changed from 4 to 3, and the page shows Price: 3.
amount. It's on the list, so the browser calls attributeChangedCallback() with the name, the old value, and the new value.Ravi buys tea from a supplier. He asks for a text message whenever the price of oolong changes. Each text says which tea, the old price, and the new price. Other teas change price too. Ravi gets no text about them, because he didn't ask.
- In real life: Ravi's list of teas to watch
- In JavaScript:
observedAttributes - In real life: A text from the supplier
- In JavaScript: A call to
attributeChangedCallback() - In real life: Which tea, the old price, and the new price
- In JavaScript:
name,oldValue, andnewValue - In real life: Teas Ravi didn't ask about
- In JavaScript: Attributes that aren't on the list
A custom element lists the attributes it cares about in static observedAttributes. The browser calls its attributeChangedCallback(name, oldValue, newValue) each time one of them is added, changed, or removed. Draw the new value there, and the element keeps up with its attributes.
Lesson 2.2 showed attributes from the outside: settings written in HTML, always as text. This lesson is the inside view. It shows how your component hears about them.
How does observedAttributes work?
observedAttributes is a static field. Static means it belongs to the class itself, not to each element. You read it on the class, as TeaPrice.observedAttributes. The Static members lesson explains static fields for any class.
The browser reads the list in customElements.define(). Lesson 3.1 said define() reads your callbacks once, right then. It reads the list at the same moment, and only once. Change the list afterwards, and nothing happens:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed to ${newValue}`); } } customElements.define("tea-price", TeaPrice); TeaPrice.observedAttributes.push("currency"); const price = document.querySelector("tea-price"); price.setAttribute("currency", "EUR"); console.log("The list:", TeaPrice.observedAttributes.join(", "));</script>- Line 5 lists only
amount. - Line 11 registers the class. The upgrade prints
amount changed to 4. - Line 12 pushes
currencyonto the class's array, afterdefine(). - Line 15 sets
currency. Nothing prints. - Line 16 prints
The list: amount, currency. The array holds both names. Yet onlyamountworks.
Why? When define() ran, it copied the list into the registry. From then on, the browser checks its own copy. It never looks at your array again. The HTML Standard's steps for define() work this way. Chrome's guidance warns about it too: names added later are silently ignored.
define() copies the list once. Line 12 changes the class's array, but the browser only ever checks its own copy.At Leaf and Kettle, a waiter takes Asha's order on a slip: one pot of green tea. He copies it into the kitchen's book. Later, Asha writes "and a scone" on her own slip. The kitchen never sees it. It cooks from its book.
- In real life: Asha's order slip
- In JavaScript: The class's
observedAttributesarray - In real life: Copying it into the kitchen's book
- In JavaScript:
customElements.define()reading the list - In real life: Writing on her slip later
- In JavaScript:
push()afterdefine() - In real life: What the kitchen cooks
- In JavaScript: The attributes that call the callback
The same goes for the callback. Add attributeChangedCallback() to the class after define(), and it never runs. Exercise 5 of lesson 3.1 showed this with connectedCallback(). Put both parts in the class before you register it.
The older way to write the list
Older tutorials write the list as a static getter. A getter is a method that runs when you read a property, here TeaPrice.observedAttributes. Getters & setters explains them. It works the same way. This one prints when it runs:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static get observedAttributes() { console.log("define() reads the list"); return ["amount"]; } attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed to ${newValue}`); } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.setAttribute("amount", "3"); price.setAttribute("amount", "5");</script>- Lines 5 to 8 are the getter. Line 6 prints, and line 7 gives back the list.
- Line 13 registers the class. The getter runs and prints
define() reads the list. - Lines 16 and 17 change
amounttwice. The getter doesn't run again.
The console prints define() reads the list once. Then come amount changed to 4, amount changed to 3, and amount changed to 5. The field style is shorter, and it works in every current browser.
Two more details come from the HTML Standard:
define()reads the list only when the class has anattributeChangedCallback(). Without the callback, the getter never even runs.- Give it an array. A plain string, like
static observedAttributes = "amount", makesdefine()throw aTypeError.
What arguments does attributeChangedCallback get?
The browser calls the callback with three arguments, in this order:
nameis the attribute's name, like"amount".oldValueis its value before the change. It'snullwhen the attribute was just added.newValueis its value after the change. It'snullwhen the attribute was just removed.
The values are strings, or null. Attributes are always text, as lesson 2.2 showed. So "4" arrives as text, not as the number 4.
The browser passes a fourth argument too, the attribute's namespace. That's a label only a few XML-style attributes carry, like the xlink in xlink:href. Ordinary HTML attributes have none, so it's null. Most code leaves it out.
Now try it. The page loads tea-price.js, in the second tab. Its callback prints every call. Line 8 of the page does one thing to the price. Pick what it does:
<p>Oolong: <tea-price amount="4">Price: 4</tea-price></p> <script src="tea-price.js"></script> <script> const price = document.querySelector("tea-price"); console.log("Line 8 runs now"); price.setAttribute("amount", "3"); console.log("Done");</script>amount changed from 4 to 3The callback gets the name, the value before, and the value after. It runs before line 8 is over, so its line comes before Done.
The first line is always amount changed from null to 4, from the upgrade on line 3. And the callback's line always comes before Done. As with the callbacks in lesson 3.3, the browser runs it before setAttribute() returns to your script.
Three choices are worth a second look:
- amount to 4 again still calls the callback, with the same old and new value. The next section explains why.
- AMOUNT in capitals works. On an HTML page,
setAttribute()makes the name lowercase first. - Set title prints nothing, because
titleisn't on the list.
Why it matters: the callback gets everything it needs. You don't have to remember the old value yourself. And a null tells you that an attribute came or went.
Why does attributeChangedCallback run when the value is the same?
Because every set counts. The DOM Standard's steps for changing an attribute never compare the old value with the new one. They set the value, then tell your element. So setAttribute("amount", "4") on a price that already has 4 still calls the callback.
That can waste work. Asha's shop refreshes every price from the server once a minute. Most prices don't change. If each refresh draws the price again, the page works for nothing. In a bigger component, a draw might build a whole table.
The fix is one line at the top of the callback:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; #draws = 0; attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; this.#draws += 1; this.textContent = `Price: ${newValue} (draws: ${this.#draws})`; } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.setAttribute("amount", "4"); price.setAttribute("amount", "4"); price.setAttribute("amount", "3");</script>- Line 6 adds a private field,
#draws, that counts the draws. A name that starts with#is private, as in lesson 3.3. - Line 9 is the guard. If the value didn't change,
returnleaves the method at once. - Lines 10 and 11 count the draw and write the price.
- Lines 17 and 18 set the same value twice. Line 19 sets a new one.
The page shows Price: 3 (draws: 2). One draw came from the upgrade, and one from line 19. Lines 17 and 18 drew nothing. Now delete line 9 and run it again. The page shows Price: 3 (draws: 4).
Every Monday, the owner sends a price card to the print shop. Most weeks, the prices are the same. A careless printer reprints every menu anyway. A careful one holds the new card next to last week's. If nothing changed, she puts the paper away.
- In real life: Sending a price card to the printer
- In JavaScript:
setAttribute() - In real life: The printer gets every card
- In JavaScript: The callback runs for every set
- In real life: Holding it next to last week's card
- In JavaScript:
if (oldValue === newValue) return; - In real life: Reprinting all the menus
- In JavaScript: Drawing the element again
Chrome's guidance for custom elements uses the same check. It also asks you to keep the callback cheap. Why it matters: the guard costs one line and saves every repeat.
Does attributeChangedCallback run before connectedCallback?
Yes, for attributes that are already on the tag. In the first example, the console printed amount changed from null to 4 before line 15 changed anything. MDN says it plainly: an observed attribute in the HTML calls the callback, even if it never changes again.
Here is the full order for a tag that waits for its class:
<p>Oolong: <tea-price amount="4" title="Hot" currency="EUR"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["currency", "amount"]; constructor() { super(); console.log("constructor"); } attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed from ${oldValue} to ${newValue}`); } connectedCallback() { console.log("connectedCallback"); } } customElements.define("tea-price", TeaPrice); console.log("define() is done");</script>- Line 1 gives the price three attributes:
amount,title, andcurrency. - Line 5 lists
currencyandamount, in that order. - Lines 7 to 16 print from the constructor and from both callbacks.
- Line 18 registers the class, and the browser upgrades the price.
The console prints five lines, in this order:
constructoramount changed from null to 4currency changed from null to EURconnectedCallbackdefine() is done
The HTML Standard's steps for an upgrade explain each line. For each attribute on the element, in order, the browser queues a call with oldValue set to null. Then, if the element is on the page, it queues connectedCallback(). Then it runs the constructor, and after it the queue. So:
- Each value arrives as if it were just added, from
null. - The order is the tag's order,
amountbeforecurrency. Your list's order doesn't matter. titleisn't on the list, so it's skipped.- All of it happens before
define()returns.
null, in the tag's order. Then connectedCallback() runs. title isn't listed, so it's skipped.On her first day at Leaf and Kettle, a new waiter finds notes on her locker. One says "table 4 wants oolong". Another says "we're out of milk". She reads each one before she walks onto the shop floor. The notes aren't news to anyone else. They're news to her.
- In real life: Starting her first day
- In JavaScript: The constructor, at the upgrade
- In real life: Each note already on the locker
- In JavaScript: Each listed attribute already on the tag
- In real life: Reading them one by one
- In JavaScript: One callback for each attribute, from
null - In real life: Walking onto the shop floor
- In JavaScript:
connectedCallback()
It isn't only upgrades. Try every way to make a price. tea-price.js prints each call. It also prints whether the price is on the page during the callback:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script src="tea-price.js"></script>connectedCallback()The tag was on the page before its class. The upgrade runs the constructor, then the callback for amount, then connectedCallback().
The order never changes: the constructor, then the callback, then connectedCallback(). What changes is where the price is. When the parser builds a tag whose class it already knows, it adds the attributes first. It puts the element on the page after. With createElement(), your setAttribute() runs the callback while the price is still off the page. In both cases, isConnected is false in the callback.
Why it matters: in attributeChangedCallback(), don't count on anything that connectedCallback() sets up. A child it adds isn't there yet. Exercise 4 shows the bug and the fix. The safe pattern is one method that draws everything from the attributes, called from both callbacks. The tea kit uses it at the end of this lesson.
What happens to attributes you don't observe?
Nothing runs. The browser checks the list before it calls you. If the name isn't on it, there's no call. The attribute is still set, and you can read it any time with getAttribute().
That's on purpose. web.dev's guide calls the list a performance choice. Attributes like class and style change all the time. Without a list, your callback would run for every one of them. So list only the attributes that change what your element shows or does. Sort these for tea-price:
amountcurrencytitlehiddenclassid
Sort each attribute of tea-price by whether it belongs in observedAttributes.
The browser already handles title, hidden, class, and id by itself. Only amount and currency change the price's own text.
Names in the list must be lowercase
HTML attribute names don't care about capital letters. The HTML parser stores them in lowercase. On an HTML page, setAttribute() does too. But the browser compares your list exactly. So a name with a capital letter never matches:
<p>Green tea <tea-cup brewTime="3"></tea-cup></p> <script> class TeaCup extends HTMLElement { static observedAttributes = ["brewTime"]; attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed to ${newValue}`); } } customElements.define("tea-cup", TeaCup); const cup = document.querySelector("tea-cup"); cup.setAttribute("brewTime", "5"); console.log("Attributes:", cup.getAttributeNames().join(", "));</script>- Line 1 writes
brewTime="3"on the tag. - Line 5 lists
brewTime, with a capital T. - Line 14 sets it again from JavaScript.
- Line 15 prints
Attributes: brewtime. That's the only line the console prints.
The callback never runs. The tag's attribute is called brewtime, and the list says brewTime. So write the names in your list in lowercase. For two words, use a hyphen, like brew-time. That's the attribute style lesson 2.2 described.
Watching any attribute with MutationObserver
Sometimes you need to know about an attribute that isn't on a list, maybe on an element you didn't write. A MutationObserver can watch any attribute of any element. It tells you a moment later, in a batch:
<p>Oolong: <tea-price amount="4">Price: 4</tea-price></p> <script> const price = document.querySelector("tea-price"); const observer = new MutationObserver((records) => { for (const record of records) console.log(`${record.attributeName} changed`); }); observer.observe(price, { attributeFilter: ["title", "class"] }); price.title = "Hot"; price.classList.add("sale"); console.log("Script done");</script>- Lines 5 to 7 make an observer. Its function prints the name of each changed attribute.
- Line 8 watches the price, but only its
titleandclass. - Lines 10 and 11 change both.
- Line 12 prints
Script done.
The console prints Script done first. Then come title changed and class changed. The observer waited until the script was over. attributeChangedCallback() runs during the change, and the observer runs after. Notice that this page never defines a class for tea-price. The observer works from outside.
Here is every case from this lesson in one place. The price lists amount and currency, and starts with amount="4". Read each row across:
| What the code does | What the callback gets |
|---|---|
setAttribute("amount", "3") | ("amount", "4", "3") |
setAttribute("amount", "4"), the value it already has. | ("amount", "4", "4"). It still runs. |
setAttribute("currency", "EUR"), the first time. | ("currency", null, "EUR") |
removeAttribute("amount") | ("amount", "4", null) |
removeAttribute("currency"), when there is no currency. | Nothing. There was nothing to remove. |
setAttribute("AMOUNT", "5") | ("amount", "4", "5"). The name is made lowercase. |
setAttribute("title", "Hot") | Nothing. title isn't on the list. |
amount="4" written on the tag, at the upgrade. | ("amount", null, "4"), before connectedCallback(). |
Can a property setter cause an endless loop?
Yes, when the setter and the callback call each other. Lesson 2.2 showed properties that reflect: setting the property writes the attribute too. Inside the class, that's a setter, a method that runs when you assign to a property, like price.amount = 3.
Here is a price whose setter reflects, and whose callback keeps the property up to date:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; #amount = 0; get amount() { return this.#amount; } set amount(value) { this.#amount = Number(value); this.setAttribute("amount", value); this.textContent = `Price: ${this.#amount}`; } attributeChangedCallback(name, oldValue, newValue) { this.amount = newValue; } } customElements.define("tea-price", TeaPrice);</script>- Lines 11 to 15 are the setter. It stores the number, writes the attribute on line 13, and writes the text.
- Lines 16 to 18 are the callback. When the attribute changes, line 17 sets the property.
Follow the upgrade. The callback sets the property. The setter sets the attribute. Setting the attribute calls the callback, even with the same value. So the callback sets the property again, and so on. Chrome stops the circle with RangeError: Maximum call stack size exceeded. The call stack is the browser's list of functions that are still running. This one filled up.
RangeError.Asha and Ravi reach the shop door at the same moment. "After you," says Asha. "No, after you," says Ravi. Each one waits for the other, so nobody goes in. It ends only when one of them sees that nothing is changing, and walks in.
- In real life: Asha saying "after you"
- In JavaScript: The callback setting the property
- In real life: Ravi saying it back
- In JavaScript: The setter setting the attribute
- In real life: Nobody moving
- In JavaScript: The same value, again and again
- In real life: One of them walking in
- In JavaScript:
if (oldValue === newValue) return;
The guard from before breaks the circle. When the setter writes the value the attribute already has, the callback sees the same old and new value, and stops:
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; #amount = 0; get amount() { return this.#amount; } set amount(value) { this.#amount = Number(value); this.setAttribute("amount", value); this.textContent = `Price: ${this.#amount}`; } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; this.amount = newValue; } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.amount = 3; console.log(price.amount, price.getAttribute("amount"));</script>- Line 17 is the new guard.
- Line 24 sets the property from outside. The setter writes the attribute. The callback sets the property once more, and the next call stops at line 17.
- Line 25 prints
3 3. The property and the attribute agree.
Chrome's guidance names this trap and this fix. Reflecting properties well has more to it: which ones to reflect, and how to turn text into numbers. Lesson 5.1, Attributes and properties, covers it in full.
Making the tea kit react to attributes
Back to Asha's sale. Ravi updates two kit files, tea-label.js and tea-price.js, so they react to their attributes. tea-price also gets a currency attribute, which you can leave out. Press each button:
<script type="importmap"> { "imports": { "tea-kit/": "./tea-kit/" } }</script> <p><tea-label name="Oolong" minutes="4"></tea-label></p><p><tea-price amount="4"></tea-price></p><button id="sale">Start the sale</button><button id="euros">Show euros</button><button id="longer">Brew longer</button> <script type="module"> import "tea-kit/index.js"; const label = document.querySelector("tea-label"); const price = document.querySelector("tea-price"); document.querySelector("#sale").onclick = () => price.setAttribute("amount", "3"); document.querySelector("#euros").onclick = () => price.setAttribute("currency", "EUR"); document.querySelector("#longer").onclick = () => label.setAttribute("minutes", "5");</script>- Lines 5 and 6 use the kit's label and price in the HTML.
- Line 12 loads the whole kit, as in lesson 3.3.
- Line 16 starts the sale:
amountbecomes 3. - Line 17 adds a currency. Line 18 makes the tea brew longer.
The page starts with Oolong: brew for 4 minutes and Price: 4. Start the sale, and it shows Price: 3. Show euros: Price: 3 EUR. Brew longer: Oolong: brew for 5 minutes.
Now open the tea-kit/tea-price.js tab:
- Line 2 lists
amountandcurrency. - Lines 4 to 6 draw the price when it joins the page. A tag with no attributes gets no callback, so this draw still matters.
- Lines 8 to 11 draw again when a listed attribute really changes. Line 9 is the guard.
- Lines 13 to 17 are
#render(), a private method. Like a private field, only the class can use it. It reads both attributes and writes the text. - Line 15 uses
??, which gives""when there's no currency. On line 16,trim()drops the space left at the end.
tea-label.js has the same shape, for name and minutes. #render() reads every attribute fresh each time. So it doesn't matter which callback runs first, or how often. The kit gains three rules:
- List every attribute that changes what the element shows, in lowercase.
- Draw from one method that reads the attributes, and call it from both callbacks.
- Skip the draw when the old and new values are the same.
tea-badge and tea-timer stay as they were. Asha loads the new kit. Now her sale prices show up the moment her script sets them.
Common mix-ups
- "
attributeChangedCallback()runs for every attribute." No. It runs only for the names inobservedAttributes. Other attributes change without calling you. - "I can add names to
observedAttributeslater." No.define()reads the list once. Names added afterwards are ignored. - "It only runs when the value really changes." No. Every set calls it, even with the same value. Compare
oldValueandnewValueyourself. - "Attributes written in the HTML don't count as changes." No. Each listed attribute on the tag calls the callback, with
oldValueset tonull. - "
connectedCallback()always runs first." No. For attributes already on the tag, the callback runs first, sometimes while the element is off the page. - "Names in the list can use capitals, like
brewTime." No. HTML stores attribute names in lowercase, and the list must match exactly. - "
newValueis a number when I writeamount="4"." No. Attribute values are always strings, ornull. - "A setter that reflects is always safe." No. If the setter and the callback call each other, they loop until a
RangeError. A same-value check stops it.
Practice exercises
Answer first, then use the hints. The solutions run live, so you can check yourself.
How many lines does the console print?
<p>Oolong: <tea-price amount="4" title="Hot"></tea-price></p>
<script>
class TeaPrice extends HTMLElement {
static observedAttributes = ["amount"];
attributeChangedCallback(name, oldValue, newValue) {
console.log(`${name} changed from ${oldValue} to ${newValue}`);
}
}
customElements.define("tea-price", TeaPrice);
const price = document.querySelector("tea-price");
price.setAttribute("title", "Very hot");
price.setAttribute("amount", "4");
price.setAttribute("amount", "3");
</script><p>Oolong: <tea-price amount="4" title="Hot"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed from ${oldValue} to ${newValue}`); } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.setAttribute("title", "Very hot"); price.setAttribute("amount", "4"); price.setAttribute("amount", "3");</script>Three. The upgrade prints amount changed from null to 4. Line 14 prints nothing, because title isn't listed. Line 15 prints amount changed from 4 to 4, because every set counts. Line 16 prints amount changed from 4 to 3.
What is the last line the console prints?
<p>Oolong: <tea-price amount="4"></tea-price></p>
<script>
class TeaPrice extends HTMLElement {
static observedAttributes = ["amount"];
attributeChangedCallback(name, oldValue, newValue) {
console.log(`${name} changed from ${oldValue} to ${newValue}`);
}
}
customElements.define("tea-price", TeaPrice);
const price = document.querySelector("tea-price");
price.removeAttribute("amount");
price.removeAttribute("amount");
</script><p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; attributeChangedCallback(name, oldValue, newValue) { console.log(`${name} changed from ${oldValue} to ${newValue}`); } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.removeAttribute("amount"); price.removeAttribute("amount");</script>amount changed from 4 to null. Line 14 removes the attribute, so newValue is null. Line 15 finds nothing to remove, so the callback doesn't run.
What does line 14 print? Then fix the class so the price follows its attribute.
<p>Oolong: <tea-price amount="4">Price: 4</tea-price></p> <script> class TeaPrice extends HTMLElement { attributeChangedCallback(name, oldValue, newValue) { this.textContent = `Price: ${newValue}`; } } customElements.define("tea-price", TeaPrice); TeaPrice.observedAttributes = ["amount"]; const price = document.querySelector("tea-price"); price.setAttribute("amount", "3"); console.log(price.textContent);</script><p>Oolong: <tea-price amount="4">Price: 4</tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; attributeChangedCallback(name, oldValue, newValue) { this.textContent = `Price: ${newValue}`; } } customElements.define("tea-price", TeaPrice); const price = document.querySelector("tea-price"); price.setAttribute("amount", "3"); console.log(price.textContent);</script>It prints Price: 4. define() read the list on line 9, when there was none, so the callback never runs. With the list inside the class, line 14 prints Price: 3.
The page looks right, but open the console. What kind of error does it show? Then fix it.
<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; connectedCallback() { this.innerHTML = "Price: <strong></strong>"; this.querySelector("strong").textContent = this.getAttribute("amount"); } attributeChangedCallback(name, oldValue, newValue) { this.querySelector("strong").textContent = newValue; } } customElements.define("tea-price", TeaPrice); document.querySelector("tea-price").setAttribute("amount", "3");</script><p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; connectedCallback() { this.#render(); } attributeChangedCallback(name, oldValue, newValue) { this.#render(); } #render() { this.innerHTML = "Price: <strong></strong>"; this.querySelector("strong").textContent = this.getAttribute("amount"); } } customElements.define("tea-price", TeaPrice); document.querySelector("tea-price").setAttribute("amount", "3");</script>A TypeError: Cannot set properties of null. At the upgrade, the callback runs before connectedCallback(), so there's no <strong> yet. #render() builds the <strong> itself, so it works whichever callback comes first.
Follow the steps in the comments. What does the console print after your fix?
<p><tea-label name="Oolong" minutes="4"></tea-label></p> <script> class TeaLabel extends HTMLElement { // 1. List name and minutes here. connectedCallback() { const name = this.getAttribute("name"); const minutes = this.getAttribute("minutes"); this.textContent = `${name}: brew for ${minutes} minutes`; } // 2. Draw again when a value really changes. } customElements.define("tea-label", TeaLabel); const label = document.querySelector("tea-label"); label.setAttribute("minutes", "5"); console.log(label.textContent);</script><p><tea-label name="Oolong" minutes="4"></tea-label></p> <script> class TeaLabel extends HTMLElement { static observedAttributes = ["name", "minutes"]; connectedCallback() { this.#render(); } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; this.#render(); } #render() { const name = this.getAttribute("name"); const minutes = this.getAttribute("minutes"); this.textContent = `${name}: brew for ${minutes} minutes`; } } customElements.define("tea-label", TeaLabel); const label = document.querySelector("tea-label"); label.setAttribute("minutes", "5"); console.log(label.textContent);</script>Oolong: brew for 5 minutes. The list makes the browser call the callback when minutes changes, and #render() draws the label again. The starter prints Oolong: brew for 4 minutes.
The page shows the time, but open the console. What kind of error does Chrome report? Then fix it.
<p>Green tea: <tea-steep seconds="30"></tea-steep></p> <script> class TeaSteep extends HTMLElement { static observedAttributes = ["seconds"]; set seconds(value) { this.setAttribute("seconds", value); this.textContent = `${value} s`; } attributeChangedCallback(name, oldValue, newValue) { this.seconds = newValue; } } customElements.define("tea-steep", TeaSteep);</script><p>Green tea: <tea-steep seconds="30"></tea-steep></p> <script> class TeaSteep extends HTMLElement { static observedAttributes = ["seconds"]; set seconds(value) { this.setAttribute("seconds", value); this.textContent = `${value} s`; } attributeChangedCallback(name, oldValue, newValue) { if (oldValue === newValue) return; this.seconds = newValue; } } customElements.define("tea-steep", TeaSteep);</script>A RangeError: Maximum call stack size exceeded. The setter writes the attribute, which calls the callback, which calls the setter. With the guard, the second call sees the same value and stops.
Check your understanding
For each question, ask which attributes are on the list, and when the browser read it.
Question 1 of 8When does the browser call
attributeChangedCallback()?Choose an answer to see the explanation.
Question 2 of 8What does this page print last, from line 12?
Read the code, then predict<p>Oolong: <tea-price amount="4"></tea-price></p> <script> class TeaPrice extends HTMLElement { static observedAttributes = ["amount"]; attributeChangedCallback(name, oldValue, newValue) { console.log(oldValue, newValue); } } customElements.define("tea-price", TeaPrice); document.querySelector("tea-price").removeAttribute("amount"); </script>Choose an answer to see the explanation.
Question 3 of 8After
customElements.define(), a script runsTeaPrice.observedAttributes.push("currency"). What happens whencurrencychanges?Choose an answer to see the explanation.
Question 4 of 8A tag in the HTML has
amount="4"before its class is defined. Whendefine()upgrades it, in what order do the methods run?Choose an answer to see the explanation.
Question 5 of 8A class lists
static observedAttributes = ["brewTime"], and the page has<tea-cup brewTime="3">. Why does the callback never run?Choose an answer to see the explanation.
Question 6 of 8Why do many components start
attributeChangedCallback()withif (oldValue === newValue) return;?Choose an answer to see the explanation.
Question 7 of 8A price lists only
amount. How can your code learn that itstitlechanged?Choose an answer to see the explanation.
Question 8 of 8A setter calls
setAttribute(), andattributeChangedCallback()calls the setter. What happens at the upgrade?Choose an answer to see the explanation.
Key takeaways
- List the attributes you care about in
static observedAttributes, in lowercase.define()reads the list once. attributeChangedCallback(name, oldValue, newValue)runs each time a listed attribute is added, changed, or removed, even with the same value.oldValueisnullfor a new attribute, andnewValueisnullfor a removed one. Values are strings.- Attributes already on the tag call it before
connectedCallback(), sometimes while the element is off the page. - Unlisted attributes never call it. Read them with
getAttribute(), or watch them with aMutationObserver. - A setter that writes the attribute and a callback that sets the property loop forever without a same-value check.
Remember the one-liner.
List the attributes you care about, and the browser calls you with the old and new value each time one is set.
Sources
The facts on this page come from these standards and docs:
- Using custom elements: Responding to attribute changes, MDN.
- HTML Standard: The define() method, WHATWG.
- HTML Standard: Custom element reactions, WHATWG.
- DOM Standard: Handle attribute changes, WHATWG.
- HTML Standard: Upgrade an element, WHATWG.
- DOM Standard: The setAttribute() method, WHATWG.
- Custom Elements v1: Observing changes to attributes, Eric Bidelman, web.dev.
- Modern Web Guidance: Custom elements, Chrome for Developers.
- Custom elements: Observing attributes, javascript.info.
- MutationObserver: observe() method, MDN.
Coming next: Moving and adopting elements. Move an element without resetting it, and handle moves between documents.