Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 39 ยท Custom Elements

Attributes and observedAttributes

Make custom elements configurable with HTML attributes. Learn observedAttributes, attributeChangedCallback, parsing strings into types and boolean attributes.

Native elements are configured with attributes: <img src="...">, <input type="email">, <details open>. Your custom elements should follow the same pattern so that anyone can configure them in plain HTML. The browser helps with one callback and one static list: attributeChangedCallback and observedAttributes.

Observing attributes

Attributes can be added, changed or removed at any time, from HTML, from script (setAttribute) or from DevTools. To react, tell the browser which attributes you care about with a static getter or field named observedAttributes, then implement attributeChangedCallback.

A greeting that reacts to name

Type in the box and the greeting updates live. Click the button and it falls back to "stranger". The console shows null as the new value when an attribute is removed.

Notes about the callback:

  • It is called only for names in observedAttributes. Changes to other attributes are silently ignored.
  • Both oldValue and newValue are strings or null. null means "the attribute was absent".
  • It also fires for the initial attributes present in the HTML, before connectedCallback. Your callback may therefore run before the element has rendered anything, so guard code that touches the shadow tree.
  • It also fires when you set an attribute to the value it already has, so compare oldValue !== newValue before doing expensive work.

Attribute values are always strings

HTML attributes carry text. count="5" is the string "5", not a number. Convert explicitly in your own code:

JavaScript
get count() {
  const raw = this.getAttribute("count");
  const n = Number(raw);
  return raw === null || Number.isNaN(n) ? 0 : n;
}

Decide what happens for bad input (a default, a clamp, a console warning) rather than letting NaN leak into your UI.

Boolean attributes

HTML boolean attributes follow the rule: present means true, absent means false, regardless of the value. <input disabled>, <input disabled=""> and even <input disabled="false"> are all disabled. Do the same:

A boolean attribute

Two helpful tools appear here. hasAttribute and toggleAttribute implement the present/absent rule. And the CSS selector :host([active]) matches when the host has that attribute, so you can restyle without any JavaScript.

Enumerated and list attributes

Sometimes an attribute accepts a fixed set of keywords, such as size="small|medium|large". Validate it:

JavaScript
static #sizes = ["small", "medium", "large"];

get size() {
  const value = this.getAttribute("size");
  return HelloButton.#sizes.includes(value) ? value : "medium";
}

For lists, keep the format simple, such as space-separated tokens (like class) or comma-separated values, and split in code. For anything complex, such as objects or arrays, prefer properties (next lesson) and treat a JSON attribute only as a convenience for HTML authors.

data-* and ARIA attributes

You are free to read any attribute, including data-*, but the callback only observes what you list. Components that forward accessibility information should also set standard ARIA attributes (for example role, aria-label) on the host or on internal elements. A later chapter covers this.

Reading attributes safely

Remember the rule from the lifecycle lesson: do not read attributes in the constructor. Use them in connectedCallback or attributeChangedCallback. If the same value is needed in several places, put a getter on the class and let the getter read the attribute.

Naming conventions

Follow the platform: lowercase attribute names. HTML attribute names are case-insensitive and are lowercased by the parser, so userName becomes username. Use single words, or hyphens such as max-items if you must, and then map to camelCase properties (maxItems) in your class.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must you add so attributeChangedCallback runs for the name attribute?

    The browser only reports attributes listed in observedAttributes.
  2. 2. What does newValue contain when an observed attribute is removed?

    Removal is reported with null, which means the attribute is absent.
  3. 3. How should a boolean attribute named active be read?

    In HTML, presence means true and absence means false, whatever the value text is.
  4. 4. Which selector styles a shadow component when it has the active attribute?

    :host([attr]) matches the host element when it has that attribute.

Summary

  • List attributes in static observedAttributes and handle them in attributeChangedCallback.
  • The callback also runs for initial attributes and receives strings or null.
  • Attribute values are strings, so parse and validate them.
  • Boolean attributes follow the present/absent rule; use hasAttribute and toggleAttribute.
  • :host([attr]) lets CSS react to attributes without extra script.

Next: Properties and Reflection