completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Reacting to attributes

Learn how attributeChangedCallback and observedAttributes let a custom element react to attribute changes, including at upgrade and before connectedCallback.

By the end, you can
  • 01
    List the attributes you care aboutWrite observedAttributes, and know that define() reads it only once.
  • 02
    Read the callback's three argumentsSay what name, oldValue, and newValue hold, and when one of them is null.
  • 03
    Handle 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:

The kit's first price misses a changePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 4 loads the kit's price. Its class reads amount only in connectedCallback(), when it joins the page.
  • Line 7 sets amount to 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:

A price that hears about its amountPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 amount to 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.

What happens on line 15. setAttribute sets amount to 3. The browser checks the class's observedAttributes list, which holds amount. So it calls attributeChangedCallback with three arguments: the name amount, the old value 4, and the new value 3.line 15setAttribute("amount", "3")["amount"]observedAttributesamount is on the listattributeChangedCallback()"amount"name"4"oldValue"3"newValue
Line 15 changes amount. It's on the list, so the browser calls attributeChangedCallback() with the name, the old value, and the new value.
Real-life analogyPrice alerts from the supplier

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, and newValue
In real life: Teas Ravi didn't ask about
In JavaScript: Attributes that aren't on the list
The main idea

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:

A name added after define()Pop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 5 lists only amount.
  • Line 11 registers the class. The upgrade prints amount changed to 4.
  • Line 12 pushes currency onto the class's array, after define().
  • Line 15 sets currency. Nothing prints.
  • Line 16 prints The list: amount, currency. The array holds both names. Yet only amount works.

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.

The class's list and the registry's copy. When define() runs on line 11, the registry copies the list, which holds amount. After line 12 pushes currency, the class's list holds amount and currency, but the registry's copy still holds only amount.the class's arraythe registry's copy["amount"]define() copies["amount"]["amount", "currency"]after line 12's push()["amount"]still only amount
define() copies the list once. Line 12 changes the class's array, but the browser only ever checks its own copy.
Real-life analogyThe kitchen copies the order

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 observedAttributes array
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() after define()
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:

The list as a static getterPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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 amount twice. 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 an attributeChangedCallback(). Without the callback, the getter never even runs.
  • Give it an array. A plain string, like static observedAttributes = "amount", makes define() throw a TypeError.

What arguments does attributeChangedCallback get?

The browser calls the callback with three arguments, in this order:

  • name is the attribute's name, like "amount".
  • oldValue is its value before the change. It's null when the attribute was just added.
  • newValue is its value after the change. It's null when 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:

Playground: what does the callback get?
Line 8 changes one attributePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
Try it yourself
The callback prints amount changed from 4 to 3

The callback gets the name, the value before, and the value after. It runs before line 8 is over, so its line comes before Done.

Pick what line 8 does to the price. tea-price.js, in the second tab, prints each call with its arguments. Each choice runs in a fresh page.

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 title isn'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:

A guard that skips the same valuePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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, return leaves 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).

Real-life analogyA careful printer checks before reprinting

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:

The calls when a price is upgradedPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Line 1 gives the price three attributes: amount, title, and currency.
  • Line 5 lists currency and amount, 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:

  1. constructor
  2. amount changed from null to 4
  3. currency changed from null to EUR
  4. connectedCallback
  5. define() 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, amount before currency. Your list's order doesn't matter.
  • title isn't on the list, so it's skipped.
  • All of it happens before define() returns.
The order of the calls when define() upgrades the price. First the constructor. Second, attributeChangedCallback for amount, from null to 4. Third, attributeChangedCallback for currency, from null to EUR. Fourth, connectedCallback. The title attribute isn't on the list, so it's skipped.1stconstructor()2ndattributeChangedCallback("amount", null, "4")3rdattributeChangedCallback("currency", null, "EUR")4thconnectedCallback()titleskipped
The upgrade calls the callback for each listed attribute on the tag, from null, in the tag's order. Then connectedCallback() runs. title isn't listed, so it's skipped.
Real-life analogyA new waiter reads the notes on her locker

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:

Playground: when does the first call come?
One way to make a pricePop out in the code editor (opens in a new tab)HTML
<p>Oolong: <tea-price amount="4"></tea-price></p> <script src="tea-price.js"></script>
ResultLoading…
Try it yourself
The callback runs on the page, before connectedCallback()

The tag was on the page before its class. The upgrade runs the constructor, then the callback for amount, then connectedCallback().

Pick how the page makes the price. tea-price.js, in the second tab, prints each call. Each choice runs in a fresh page.

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:

On the list, or off it?
  • amount
  • currency
  • title
  • hidden
  • class
  • id
Try it yourself
0 of 6 correct

Sort each attribute of tea-price by whether it belongs in observedAttributes.

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

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:

A camelCase name that never matchesPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

Watching title and class from outsidePop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • Lines 5 to 7 make an observer. Its function prints the name of each changed attribute.
  • Line 8 watches the price, but only its title and class.
  • 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 callback gets
What the code doesWhat 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:

A setter and a callback that call each other (an error on purpose)Pop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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.

A circle with no end. attributeChangedCallback sets the amount property on line 17. The setter calls setAttribute on line 13. setAttribute calls attributeChangedCallback again, even with the same value. Around and around, until Chrome reports a RangeError.attributeChangedCallback()line 17set amount(value)line 13setAttribute()same value, still callsagain and again, until RangeError
Each step leads to the next, and a same-value set still calls the callback. Nothing breaks the circle, so Chrome stops it with a RangeError.
Real-life analogyAfter you, no, after you

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:

The same class with a guardPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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:

The tea kit's label and price, changed by buttonsPop out in the code editor (opens in a new tab)HTML
<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>
ResultLoading…
  • 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: amount becomes 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 amount and currency.
  • 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 in observedAttributes. Other attributes change without calling you.
  • "I can add names to observedAttributes later." 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 oldValue and newValue yourself.
  • "Attributes written in the HTML don't count as changes." No. Each listed attribute on the tag calls the callback, with oldValue set to null.
  • "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.
  • "newValue is a number when I write amount="4"." No. Attribute values are always strings, or null.
  • "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.

Exercise 1 · Warm-upCount the calls

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>

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

    Exercise 2 · Warm-upRemove the amount twice

    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>

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

      Exercise 3 · PracticeFind the bug in the late list

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

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

        Exercise 4 · PracticeFind the bug in the bold price

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

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

          Exercise 5 · ChallengeMake the label react

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

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

            Exercise 6 · ChallengeBreak the loop

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

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

              Check your understanding

              For each question, ask which attributes are on the list, and when the browser read it.

              The attributeChangedCallback quiz · 8 questionsScore: first tries count
              1. Question 1 of 8When does the browser call attributeChangedCallback()?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does this page print last, from line 12?

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

              3. Question 3 of 8After customElements.define(), a script runs TeaPrice.observedAttributes.push("currency"). What happens when currency changes?

                Choose an answer to see the explanation.

              4. Question 4 of 8A tag in the HTML has amount="4" before its class is defined. When define() upgrades it, in what order do the methods run?

                Choose an answer to see the explanation.

              5. 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.

              6. Question 6 of 8Why do many components start attributeChangedCallback() with if (oldValue === newValue) return;?

                Choose an answer to see the explanation.

              7. Question 7 of 8A price lists only amount. How can your code learn that its title changed?

                Choose an answer to see the explanation.

              8. Question 8 of 8A setter calls setAttribute(), and attributeChangedCallback() 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.
              • oldValue is null for a new attribute, and newValue is null for 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 a MutationObserver.
              • 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:

              Coming next: Moving and adopting elements. Move an element without resetting it, and handle moves between documents.

              CompleteFrontend Clear concepts. Working examples.