Course contentsShow
← Web Development
Lesson 2451 of 2,98244. Web ComponentsFree lesson

Observed Attributes

Using the static observedAttributes array to specify which HTML attributes trigger attributeChangedCallback.

Observed Attributes

You'll learn how to tell a custom element which HTML attributes it should watch for changes.

What Are Observed Attributes?

When you build a custom element, you often want it to react when certain HTML attributes change—like updating its display when a disabled or color attribute is modified. By default, custom elements don't automatically watch any attributes. You must explicitly declare which ones matter.

The observedAttributes getter does exactly this: it returns an array of attribute names. When any of these attributes change (added, removed, or modified), the browser automatically calls your element's attributeChangedCallback.

How It Works

Define a static getter named observedAttributes in your custom element class. Return an array of lowercase attribute names you want to monitor:

class MyComponent extends HTMLElement {
  static get observedAttributes() {
    return ['color', 'disabled', 'size'];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    console.log(`${name} changed from "${oldValue}" to "${newValue}"`);
    // React to the change here
  }
}

customElements.define('my-component', MyComponent);

Now, whenever someone changes <my-component color="red"> to <my-component color="blue">, your callback fires with name='color', oldValue='red', and newValue='blue'.

Think of It Like a Subscription

Imagine a newsletter service: you only get emails about topics you've subscribed to. Similarly, observedAttributes is your subscription list—only changes to those attributes trigger notifications (callbacks).

Key Takeaway: Use the static observedAttributes getter to return an array of attribute names you want to monitor; only those will trigger attributeChangedCallback when changed.