completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

Talking to a component from JavaScript

Talk to a web component from JavaScript: set attributes and properties, call methods, listen for web component events, and wait with whenDefined().

By the end, you can
  • 01
    Set attributes and propertiesSay why an attribute always holds text while a property can hold any value, and choose the right one for each job.
  • 02
    Call methods and listen for eventsCall a component's methods, listen for its exact event names, read event.detail, and stop listening with an AbortController.
  • 03
    Wait for the definitionUse customElements.whenDefined() before you call a method on a tag whose file may not have loaded yet.

How do you talk to a web component from JavaScript?

Ravi's menu page for Leaf and Kettle is live. He built it in the last lesson, from Web Awesome's ready-made tags, with no JavaScript at all. Now the owner wants more. Customers should rate each tea, and the page should thank them. A brewing guide should open from a script, and the page should know when it closes.

The tags work in HTML. But how does a script set them, ask them to do things, and hear back from them?

You talk to a web component the way you talk to any element. Set its attributes and properties, call its methods, and listen for its events with addEventListener(). Before you call a method, wait for the tag's class with customElements.whenDefined().

Here is the first step. A rating, and a line of text that follows it:

A rating that thanks the customerPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><p>You gave Green tea 4 stars.</p> <script type="module">  await customElements.whenDefined("wa-rating");  const rating = document.querySelector("wa-rating");  const note = document.querySelector("p");  rating.addEventListener("change", () => {    note.textContent = `You gave Green tea ${rating.value} stars.`;  });</script>
ResultLoading…
  • Lines 1 and 2 load Web Awesome, exactly as in lesson 2.1: the stylesheet and the loader.
  • Line 4 is a <wa-rating>: a row of five stars. Its value="4" attribute lights up four of them.
  • Line 5 is a plain paragraph.
  • Line 8 waits until the rating's class has loaded. The section on whenDefined() explains why.
  • Lines 9 and 10 find the rating and the paragraph.
  • Line 11 listens for change, an event the rating fires when a customer picks a star.
  • Line 12 reads rating.value, the rating's current number, and writes it into the paragraph.

Click the second star. The paragraph changes to You gave Green tea 2 stars. Three of the four ways to talk to a component are in this one example: an attribute, a property, and an event. The fourth is a method you call. This picture shows all four:

Four ways to talk to a component. A window called your page holds four cards. The first, summary equals Green tea, is an attribute in the HTML. The second, details.open = true, is a property in JavaScript. The third, details.show(), is a method call. The fourth, wa-show, is an event that comes back. Three arrows go from the first three cards into a large card, wa-details. One arrow comes back out of it, to the wa-show card.your pageattribute, in the HTMLsummary="Green tea"property, in JavaScriptdetails.open = truemethod, a calldetails.show()event, comes backwa-showthe component<wa-details>
Three ways go in: an attribute in the HTML, a property, and a method call. One comes back out: an event, which your listener hears.
Real-life analogyOrdering at a café counter

At Leaf and Kettle's counter, you can talk to the barista in a few ways. You can write your order on a slip. You can tell them a detail out loud. You can ask them to do something right now. And when your tea is ready, they call your name, and you listen for it.

In real life: The order you write on the slip
In JavaScript: An attribute in the HTML, like value="4"
In real life: Telling the barista "make it large"
In JavaScript: Setting a property, like rating.value = 2
In real life: Asking "can you warm it now?"
In JavaScript: Calling a method, like details.show()
In real life: The barista calling your name
In JavaScript: An event, like change, that your listener hears
The main idea

A web component is an element, so you talk to it like one. Attributes and properties go in. Methods ask it to act. Events come back out to your listeners. Wait with whenDefined() until its class has loaded.

These four ways are the same tables you read in a component's docs in lesson 2.1. That lesson read them. This one uses them from a script.

What's the difference between attributes and properties?

An attribute is a setting written in the HTML, like value="4". A property is a value stored on the element object in JavaScript, like rating.value. They often share a name. They are still two different places. The Attributes and properties lesson in the JavaScript path shows this for built-in tags. Here it is on a component:

The same setting, as an attribute and as a propertyPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating> <script type="module">  await customElements.whenDefined("wa-rating");  const rating = document.querySelector("wa-rating");  console.log(typeof rating.getAttribute("value"));  console.log(typeof rating.value);</script>
ResultLoading…
  • Line 4 writes the attribute in the HTML.
  • Lines 7 and 8 wait for the class, then find the rating.
  • Line 9 reads the attribute with getAttribute() and asks for its type. It prints string.
  • Line 10 reads the property. It prints number.

An attribute is always text. HTML is text, so there's nothing else it can be. The component reads that text and keeps a real number in its property. Why it matters: when you need the number, read the property.

Real-life analogyThe recipe card and the pot on the stove

In Leaf and Kettle's kitchen, a recipe card says "brew for 4 minutes". That's the plan, in words. The pot on the stove is what's really happening. The cook can take it off after 2 minutes, and the card still says 4. If the owner writes a new time on the card, the cook follows the new time.

In real life: The recipe card, with words written on it
In JavaScript: The attribute value="4": always text
In real life: The pot on the stove right now
In JavaScript: The property rating.value: the current value
In real life: Taking the pot off early
In JavaScript: rating.value = 2: the card still says 4
In real life: Writing a new time on the card
In JavaScript: setAttribute("value", 2): the cook follows it

Now try it. Pick a line, and watch the stars and the console:

Playground: attribute or property?
One line sets the rating's attribute or propertyPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating> <script type="module">  await customElements.whenDefined("wa-rating");  const rating = document.querySelector("wa-rating");  rating.value = 2;  console.log("The attribute says", rating.getAttribute("value"));  console.log("The property says", rating.value);</script>
ResultLoading…
Try it yourself
The result shows: Two stars. The console prints "The attribute says 4" and "The property says 2".

Line 9 sets the property. The stars follow it, but the attribute keeps the starting value from line 4. wa-rating doesn't copy its value back into the HTML.

Only line 9 changes. Lines 10 and 11 print the attribute and the property after it runs. Each choice runs in a fresh page.

Two things stand out. Setting the property moved the stars but left the attribute at 4. And anything you pass to setAttribute() becomes text, even an object. A function, like the one getSymbol takes, can only go in a property.

Two places for one setting. A window called html holds a card, value equals 4 in quotes, labelled text in the HTML. An arrow labelled copied in leads to a cart called rating, which holds a card, value: 2, labelled any value on the element. A note under the window says rating.value = 2 leaves it at 4.text, in the HTMLhtmlvalue="4"rating.value = 2leaves it at 4copied inany value, on the elementvalue: 2rating
The attribute lives in the HTML and holds text. The property lives on the element and holds a real value. Setting rating.value = 2 changed only the property, so the HTML still says 4.

The object case is worth seeing on its own. This code needs no page, so it runs as plain JavaScript:

An object in an attribute, and in a propertyPop out in the code editor (opens in a new tab)JavaScript
const card = document.createElement("div");
const order = { tea: "Green tea", cups: 2 };
card.setAttribute("data-order", order);
console.log(card.getAttribute("data-order"));
card.order = order;
console.log(card.order.cups);
  • Line 1 makes a div. Line 2 makes an order object.
  • Line 3 puts the object in an attribute. Line 4 prints [object Object]. The tea and the cups are gone.
  • Line 5 puts the same object in a property. Line 6 prints 2. The object arrived whole.

Why it matters: lists, objects, and functions go in properties. Attributes are for short settings you could type in HTML.

Attribute names and property names

Names follow two styles. Attribute names are lowercase with hyphens, like light-dismiss. Property names use camelCase: no hyphens, and a capital letter starts each new word, like lightDismiss. The docs table shows both, the property on top. And only property names care about capital letters:

Two name styles, and capital lettersPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog label="Brewing guide" light-dismiss></wa-dialog> <script type="module">  await customElements.whenDefined("wa-dialog");  const dialog = document.querySelector("wa-dialog");  console.log(dialog.lightDismiss);  console.log(dialog["light-dismiss"]);  dialog.setAttribute("LABEL", "How to brew");  console.log(dialog.label);  console.log(dialog.Label);</script>
ResultLoading…
  • Line 4 turns on light-dismiss in the HTML.
  • Line 9 reads it as dialog.lightDismiss. It prints true.
  • Line 10 tries the attribute's name as a property. It prints undefined. No property has that name.
  • Line 11 sets an attribute called LABEL, in capitals. The browser stores it as label.
  • Line 12 prints How to brew. Line 13 prints undefined, because Label with a capital L is a different property.

When a property copies itself into the attribute

Some properties reflect: when you set them, the component writes the attribute too. The docs mark them in a Reflects column. wa-details's open reflects. But Web Awesome writes the attribute a moment later, not on the same line:

A property that reflects, a moment laterPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="How to brew green tea">  Use water at 80 degrees. Brew for 3 minutes.</wa-details> <script type="module">  await customElements.whenDefined("wa-details");  const details = document.querySelector("wa-details");  details.open = true;  console.log("Right away:", details.hasAttribute("open"));  await details.updateComplete;  console.log("After the update:", details.hasAttribute("open"));</script>
ResultLoading…
  • Line 11 sets the property. The guide opens.
  • Line 12 asks for the attribute at once. It prints Right away: false.
  • Line 13 waits for updateComplete, a promise every Web Awesome component has. It is ready when the component has finished its next update.
  • Line 14 prints After the update: true.

Web Awesome is built with Lit, a library that saves up changes and applies them together. Its usage guide shows this same wait. Why it matters: read the attribute after updateComplete, or just read the property.

Read each row across: the question, then the answer for an attribute and for a property.

An attribute or a property?
What you want to knowAn attributeA property
Where do you write it?In the HTML, like value="4", or with setAttribute().In JavaScript, like rating.value = 4.
What can it hold?Only text. A number or an object is turned into text.Any value: a number, an object, an array, or a function.
How is its name written?In lowercase, with hyphens, like light-dismiss. Capital letters are ignored.In camelCase, like lightDismiss. Capital letters matter.
Does it show in the HTML?Yes. DevTools' Elements panel shows it.No, unless the component copies it back into an attribute.
Is it there before the class loads?Yes. The browser keeps it from the HTML.No. The class brings it, so it reads undefined until then.

How do you call a web component's methods?

A method is a function that belongs to the element. You call it with a dot and the call brackets, like details.show(). The Methods table in the docs lists the ones you may use. For wa-details, a box that opens to show more, it lists two: show() and hide().

Open and close the guide with two methodsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="How to brew green tea">  Use water at 80 degrees. Brew for 3 minutes.</wa-details><wa-button id="show">Show the guide</wa-button><wa-button id="hide">Hide it</wa-button> <script type="module">  const details = document.querySelector("wa-details");  document.querySelector("#show").addEventListener("click", async () => {    await details.show();    console.log("The guide is open");  });  document.querySelector("#hide").addEventListener("click", () => details.hide());</script>
ResultLoading…
  • Lines 4 to 6 are the guide, closed. Lines 7 and 8 are two buttons.
  • Line 12 runs a function when the first button is clicked. async lets it use await.
  • Line 13 calls show(). It opens the guide and gives back a promise. The promise is ready when the opening animation has finished. await waits for it.
  • Line 14 prints The guide is open, once the animation is done.
  • Line 16 calls hide() when the second button is clicked.

Click Show the guide. The guide opens, and the console prints The guide is open. Click Hide it, and it closes. There is no whenDefined() here. The methods run only on a click, and by then the file has loaded.

Real-life analogyA light switch and a doorbell

A light switch stays up or down. Anyone can walk past and see whether the light is on. A doorbell is different. You press it, and something happens right now: someone comes to the door. You can wait at the door until they open it.

In real life: The light switch, which stays where you put it
In JavaScript: A property, like details.open: you can read it back
In real life: Pressing the doorbell
In JavaScript: A method call, like input.focus(): it starts something now
In real life: Waiting for someone to open the door
In JavaScript: await details.show(): waiting until the job is done

wa-details has both. open is the switch, and show() is the doorbell. Some jobs have only a method, because no setting could do them. Moving the cursor into a box is one:

Put the cursor in the box and select its textPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-input label="Name for the order" value="Ravi"></wa-input><wa-button>Change the name</wa-button> <script type="module">  const input = document.querySelector("wa-input");  document.querySelector("wa-button").addEventListener("click", () => {    input.focus();    input.select();  });</script>
ResultLoading…
  • Line 4 is a text box, <wa-input>, that already holds Ravi.
  • Line 10 calls focus(). The cursor moves into the box.
  • Line 11 calls select(). The Input docs say it selects all the text.

Click Change the name, then type Asha. Your typing replaces Ravi, because it was selected.

Other components have no methods for the job at all. The Dialog docs list no method for opening. Their examples open it with a property, dialog.open = true. Why it matters: check the Methods table before you guess. Never call a method the docs don't list.

How do you listen for web component events?

An event is a message an element sends when something happens. You hear it with addEventListener(), as on any element. The first part is the event's name. Take it exactly from the component's Events table. For wa-dialog, the table lists wa-show, wa-after-show, wa-hide, and wa-after-hide.

Hear the guide open and closePop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">  Use water at 80 degrees. Brew for 3 minutes.  <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module">  const dialog = document.querySelector("wa-dialog");  dialog.addEventListener("wa-show", () => console.log("The guide opened"));  dialog.addEventListener("wa-hide", (event) => {    console.log("Closed by", event.detail.source.localName);  });</script>
ResultLoading…
  • Lines 4 to 7 are the guide, a wa-dialog, with a Close button in its footer.
  • Line 8 opens it, with the data-dialog attribute from lesson 2.1.
  • Line 12 listens for wa-show and prints The guide opened.
  • Line 13 listens for wa-hide. Its function gets the event object, here called event.
  • Line 14 reads event.detail.source: the element that closed the guide. It prints that element's tag name.

Open the guide, and the console prints The guide opened. Press Close, and it prints Closed by wa-button. Open it again and press the Escape key. Now it prints Closed by dialog. The source is the browser's own <dialog> element, inside the component. The docs say this source means the Escape key or your own code closed it.

Real-life analogyThe buzzer that comes with your order

At a busy café, you order and get a small buzzer. You don't stand at the counter asking "Is it ready?". You sit down. When your tea is ready, the buzzer buzzes, and its screen shows your order number.

In real life: Taking a buzzer
In JavaScript: addEventListener("wa-hide", …)
In real life: The buzz
In JavaScript: The event, fired by the component
In real life: The number on its screen
In JavaScript: event.detail, the data the event carries
In real life: A buzzer that works only once
In JavaScript: The once: true option
In real life: Handing all your buzzers back
In JavaScript: controller.abort()

The name must match exactly

A listener with the wrong name never runs, and nothing tells you. Try five names on the same page:

Playground: which name does the page hear?
A listener for one event namePop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">  Use water at 80 degrees.  <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module">  const dialog = document.querySelector("wa-dialog");  dialog.addEventListener("wa-hide", () => console.log("Heard it"));</script>
ResultLoading…
Try it yourself
Open and close the guide: the console prints "Heard it".

wa-hide is the name in the Dialog docs' Events table. Close the guide, and the console prints Heard it.

Only the name on line 12 changes. Open the guide with its button, then close it with Close or the Escape key. Each choice runs in a fresh page.

Only wa-hide works. Web Awesome puts wa- in front of its own events. Names care about capital letters, as MDN says. And Shoelace's old sl- names are gone. Why it matters: copy the name from the Events table, letter for letter.

Where an event keeps its data

A component can send its own events as a CustomEvent. The DOM standard gives it one extra property, detail, for any data the event carries. The Custom events lesson shows how one is made. Web Awesome's events have their own classes, like WaHideEvent. They put their data in detail too. So event.detail.source works on wa-hide, and event.detail.value works on the rating's wa-hover. An event with no data, like the rating's change, has no detail. Read rating.value instead, as line 12 of the first example does.

Listening once, and stopping later

addEventListener() takes a third part: an object of options. Two of them help on a component's page.

One listener runs once, and one button stops two morePop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button><wa-button id="stop">Stop listening</wa-button> <script type="module">  const dialog = document.querySelector("wa-dialog");  const controller = new AbortController();  dialog.addEventListener("wa-show", () => console.log("Welcome!"), { once: true });  dialog.addEventListener("wa-show", () => console.log("Opened"), { signal: controller.signal });  dialog.addEventListener("wa-hide", () => console.log("Closed"), { signal: controller.signal });  document.querySelector("#stop").addEventListener("click", () => controller.abort());</script>
ResultLoading…
  • Line 10 makes an AbortController: an object with one job, to send a stop signal when you call its abort() method.
  • Line 11 adds once: true. The browser removes this listener after it runs one time.
  • Lines 12 and 13 pass signal: controller.signal. Each listener is tied to the controller.
  • Line 14 calls controller.abort() on a click. The browser removes both tied listeners at once.

Open and close the guide. The console prints Welcome!, Opened, and Closed. Do it again: only Opened and Closed. Click Stop listening, and the next open and close print nothing. Why it matters: one abort() call removes many listeners, so you don't have to keep every function to remove it later. The Cancellation with AbortController lesson uses the same object to stop requests.

Do web component events cross the shadow DOM?

Some do, and some don't. It depends on two settings each event is made with:

  • bubbles: when it's true, the event travels up through the element's parents, as Bubbling and capturing showed. It's like a message passed from a table, to the counter, to the manager.
  • composed: when it's true, the event can leave the shadow root it started in. A shadow root is a component's private tree, from lesson 1.1.

Both start as false, the DOM standard says. Web Awesome makes wa-show and wa-hide with both set to true. So you don't have to listen on each element. One listener on the whole page hears them all:

One listener for every guide on the pagePop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="Green tea">Brew for 3 minutes.</wa-details><wa-details summary="Black tea">Brew for 4 minutes.</wa-details> <script type="module">  document.addEventListener("wa-show", (event) => {    console.log("Opened:", event.target.summary);  });</script>
ResultLoading…
  • Lines 4 and 5 are two guides, one for each tea.
  • Line 8 listens on document, the top of the page.
  • Line 9 reads event.target, the element the event came from. It prints its summary, the guide's title.

Open the green tea guide, then the black tea one. The console prints Opened: Green tea, then Opened: Black tea. This is event delegation, and it works because the event bubbles.

The path of two events. Cards are stacked from top to bottom: document, body, and wa-dialog. Under them, a window called shadow root holds a card, dialog. On the left, an arrow labelled wa-hide, bubbles true, composed true, runs from wa-dialog up past body to document. On the right, inside the shadow root, a short arrow labelled close, bubbles false, composed false, rises from dialog and stops inside the shadow root.document<body><wa-dialog>shadow root<dialog>wa-hidebubbles: truecomposed: trueclosebubbles: falsecomposed: false
Web Awesome fires wa-hide on the wa-dialog element itself, and it bubbles up to the body and the document. The inner <dialog>'s close event never leaves the shadow root.

The picture shows why close failed in the playground. wa-dialog has a browser <dialog> inside its shadow root. That <dialog> fires close, but close doesn't bubble and isn't composed. It never leaves the shadow root. Web Awesome fires wa-hide on the outer element, where your page can hear it.

From inside another shadow root

composed matters most when the library's tag sits inside another component. Here a wa-details lives in the shadow root of <tea-guide>, like the button inside tea-order in lesson 2.1:

An event from inside a shadow rootPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/components/details/details.js"></script> <tea-guide></tea-guide> <script>  class TeaGuide extends HTMLElement {    constructor() {      super();      const shadow = this.attachShadow({ mode: "open" });      shadow.innerHTML = '<wa-details summary="How to brew">Brew for 3 minutes.</wa-details>';    }  }  customElements.define("tea-guide", TeaGuide);   document.addEventListener("wa-show", (event) => {    console.log("Opened, says", event.target.localName);  });</script>
ResultLoading…
  • Line 2 loads the details file directly. The autoloader can't see inside a shadow root, as lesson 2.1 showed.
  • Lines 7 to 14 define tea-guide. Line 11 puts a wa-details in its shadow root.
  • Line 16 listens on document. Line 17 prints the target's tag name.

Open the guide. The console prints Opened, says tea-guide. The event crossed out of the shadow root, because it's composed. Outside, the browser shows the host, tea-guide, as the target, and keeps the inside private. This is called retargeting. The lesson on event retargeting follows the whole path.

Read each row across: the event, then whether it bubbles, then whether it leaves a shadow root.

Which events reach a listener outside the component?
Which eventDoes it bubble?Does it leave a shadow root?
wa-show and wa-hide, from wa-dialog and wa-detailsYes. A listener on the document hears it.Yes. It's composed.
wa-hover, from wa-ratingYes. A listener on the document hears it.Yes. It's composed.
change, from wa-ratingYes. A listener on the document hears it.Yes. It's composed.
close, from the <dialog> inside wa-dialogNo. It doesn't travel up through the parents.No. It stays inside the component.

Why it matters: if a listener on a parent never runs, check whether the event bubbles. Or listen on the component itself.

What does customElements.whenDefined() do?

Ravi wants the brewing guide to open as soon as the page loads. He moves details.show() to the top of his script. The console shows an error, and the guide stays shut. What went wrong?

Timing. The autoloader is a module script. It runs after the HTML has been read, and then it starts loading each component's file. Ravi's script runs before those files arrive. At that moment, <wa-details> is a tag the browser doesn't know yet, as in lesson 1.1. It's a plain HTML element, with no show(). Try three ways to start:

Playground: too early, or after whenDefined()?
A script that may run before the class arrivesPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-details summary="How to brew green tea">  Use water at 80 degrees. Brew for 3 minutes.</wa-details> <script type="module">  const details = document.querySelector("wa-details");  console.log("Defined yet?", customElements.get("wa-details") !== undefined);  // No waiting  details.show();</script>
ResultLoading…
Try it yourself
The guide stays closed, and the console shows TypeError: details.show is not a function.

Line 10 prints Defined yet? false: the file for wa-details hasn't arrived. Until it does, the tag is a plain HTML element with no show() method. So line 12 throws a TypeError, and the guide stays closed.

Lines 11 and 12 change. Line 10 always prints whether wa-details is defined when the script starts. Each choice runs in a fresh page.

Calling the method too early throws TypeError: details.show is not a function. Waiting fixes it. customElements.whenDefined("wa-details") gives back a promise. The promise is ready once wa-details is defined and every one on the page is upgraded. await pauses the script until then.

Three moments in a row. First, the HTML is read: under it, details.show() and the word TypeError. An arrow leads to the second, the file loads: under it, the tag waits, undefined. An arrow leads to the third, define() runs: under it, whenDefined() resolves, and show() works.1. HTML is read2. the file loads3. define() runsdetails.show()TypeErrorthe tag waitsundefinedwhenDefined()resolvesshow() works
At first, wa-details is a tag with no class, so show() throws. When its file loads, define() upgrades it, and the promise from whenDefined() resolves. Code after the await runs from there.
Real-life analogyAsking the shop to call when it's in

Ravi wants a teapot the shop doesn't have yet. He leaves his number and asks them to call when it comes in. He doesn't phone every hour. If it's already on the shelf, they tell him straight away.

In real life: The teapot that hasn't arrived
In JavaScript: The class for wa-details, still loading
In real life: Leaving your number
In JavaScript: customElements.whenDefined("wa-details")
In real life: The call that says "it's here"
In JavaScript: The promise fulfills, with the class
In real life: A teapot already on the shelf
In JavaScript: A tag that's already defined: the promise is ready at once

What the promise gives you

The promise fulfills with the class itself:

whenDefined() gives back the classPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating> <script type="module">  const Rating = await customElements.whenDefined("wa-rating");  console.log(Rating.name);  console.log(Rating === customElements.get("wa-rating"));  console.log(document.querySelector("wa-rating") instanceof Rating);</script>
ResultLoading…
  • Line 7 waits for wa-rating and keeps what the promise gives in Rating.
  • Line 8 prints the class's name, WaRating.
  • Line 9 prints true: it's the class customElements.get() returns.
  • Line 10 prints true: the rating on the page is now built from that class.

Two mistakes behave very differently. A name with no hyphen isn't a valid custom element name. Then the promise fails at once with a SyntaxError:

A name with no hyphen fails at oncePop out in the code editor (opens in a new tab)HTML
<script type="module">  try {    await customElements.whenDefined("rating");  } catch (error) {    console.log(error.name);  }</script>
ResultLoading…

Line 3 asks for rating, with no hyphen. Line 5 prints SyntaxError. But a valid name that is spelled wrong, like wa-ratng, fails silently. Nothing ever defines it, so the promise waits forever, with no error. Why it matters: when code after an await never runs, check the spelling of the tag.

Properties set too early

In the playground, setting open early worked. Web Awesome is built with Lit, and Lit keeps a property you set before the upgrade, then hands it to the class. A component written by hand may not. Here is a small version of tea-price with an amount property and nothing else:

A property set before the class arrivesPop out in the code editor (opens in a new tab)HTML
<p>Green tea. <tea-price></tea-price></p> <script>  const price = document.querySelector("tea-price");  price.amount = 4;</script><script type="module" src="tea-price.js"></script>
ResultLoading…
  • Line 1 puts <tea-price> in a paragraph.
  • Line 5 sets amount in a classic script, which runs at once.
  • Line 7 loads the class. A module script runs later, after the HTML is read.
  • In the tea-price.js tab, lines 2 to 4 are a setter: a function that runs when someone sets amount. It writes Price: 4.

The result shows Green tea. and no price. Line 5 ran first, on a plain element, so it made an ordinary property called amount. That property now sits in front of the class's setter, which never runs. Set it after await customElements.whenDefined("tea-price"), and the result shows Green tea. Price: 4. Stage 2 shows component authors how to guard against this.

Why it matters: before a component's class arrives, its methods are missing, and its properties may not stick. Wait with whenDefined() whenever your code runs as the page loads.

Open a brewing guide from JavaScript

Ravi now has everything the owner asked for. First, sort each job by the way you'd do it:

Attribute, property, method, or event?
  • Show 4 stars when the page first loads
  • Close the guide when someone clicks outside it
  • Give the rating a function that draws dots
  • Open the guide from a click handler
  • Open the details and wait until it has finished opening
  • Put the cursor in the name box
  • Know when the guide closes
  • Know which star the pointer is on
Try it yourself
0 of 8 correct

Sort each job on Ravi's menu page by the way you'd talk to the component.

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

Here is his menu card. It has a rating and a button that opens the guide. The page logs what happens, and one button stops all the logging:

Leaf and Kettle's menu card, talking to its componentsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-card>  <strong slot="header">Green tea</strong>  Brew for 3 minutes. Price: 4  <wa-rating label="Rate green tea" value="4"></wa-rating>  <wa-button slot="footer" id="open-guide">Brewing guide</wa-button>  <wa-button slot="footer" id="stop">Stop logging</wa-button></wa-card> <wa-dialog id="guide" label="Brewing guide">  Use water at 80 degrees. Brew for 3 minutes.  <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog> <script type="module">  const rating = document.querySelector("wa-rating");  const dialog = document.querySelector("#guide");  const controller = new AbortController();  const { signal } = controller;   document.querySelector("#open-guide").addEventListener("click", () => {    dialog.open = true;  });  rating.addEventListener("change", () => console.log("Rated", rating.value), { signal });  dialog.addEventListener("wa-show", () => console.log("Guide opened"), { signal });  dialog.addEventListener("wa-hide", (event) => {    console.log("Guide closed by", event.detail.source.localName);  }, { signal });  document.querySelector("#stop").addEventListener("click", () => controller.abort());</script>
ResultLoading…
  • Lines 4 to 10 are a card. Line 7 is the rating. Lines 8 and 9 are two buttons in the card's footer.
  • Lines 12 to 15 are the guide.
  • Lines 20 and 21 make one AbortController and take its signal out into a variable of its own.
  • Lines 23 to 25 open the guide on a click, with the open property.
  • Lines 26 to 30 add three listeners: the rating's change, then wa-show and wa-hide. Each one is tied to the same signal.
  • Line 31 calls abort() when Stop logging is clicked.

Click the fifth star. The console prints Rated 5. Open the guide and press Close: Guide opened, then Guide closed by wa-button. Now click Stop logging. The stars and the guide still work, but the console stays quiet. One call removed all three listeners.

This script has no whenDefined(), and it doesn't need one. addEventListener() works on any element, defined or not. And the only property it sets is set on a click.

Common mix-ups

  • "An attribute and a property with the same name are the same thing." No. The attribute is text in the HTML, and the property is a value on the element. Setting rating.value left the attribute at 4.
  • "You can pass an object or a list through an attribute." No. It becomes the text [object Object]. Use a property.
  • "After you set a property, the attribute changes on the next line." No. Web Awesome writes reflected attributes a moment later. Wait for updateComplete.
  • "A listener for hide hears wa-hide." No. The name must match exactly, prefix and capital letters included.
  • "Every event inside a component reaches the page." No. Only composed events leave a shadow root. The inner <dialog>'s close never does.
  • "The browser waits for a component's class before running your script." No. Your script can run first. Wait with customElements.whenDefined().
  • "whenDefined() tells you when a tag name is wrong." No. Only a name with no hyphen fails. A misspelled valid name waits forever.

Practice exercises

Answer first, then use the hints. Every result runs live, so you can check yourself.

Exercise 1 · Warm-upThe attribute after the property

What does line 10 print?

<link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="3"></wa-rating> <script type="module">  await customElements.whenDefined("wa-rating");  const rating = document.querySelector("wa-rating");  rating.value = 5;  console.log(rating.getAttribute("value"));</script>
ResultLoading…

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

    Exercise 2 · Warm-upA listener that never runs

    Open and close the guide. Nothing prints. Which name should line 12 listen for?

    <link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">  Use water at 80 degrees.  <wa-button slot="footer" data-dialog="close">Close</wa-button></wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button> <script type="module">  const dialog = document.querySelector("wa-dialog");  dialog.addEventListener("hide", () => console.log("Heard it"));</script>
    ResultLoading…

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

      Exercise 3 · PracticeOpen the guide from your script

      Replace the comment on line 10 so the button opens the guide. Which property did you set?

      <link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button>Brewing guide</wa-button> <script type="module">  const dialog = document.querySelector("wa-dialog");  document.querySelector("wa-button").addEventListener("click", () => {    // Open the dialog here  });</script>
      ResultLoading…

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

        Exercise 4 · PracticeRead the event's data

        Point at a star. The paragraph says undefined. Fix line 11. Where does the hovered value live?

        <link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><p>Point at a star.</p> <script type="module">  const rating = document.querySelector("wa-rating");  const note = document.querySelector("p");  rating.addEventListener("wa-hover", (event) => {    note.textContent = `You're pointing at ${event.value} of 5.`;  });</script>
        ResultLoading…

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

          Exercise 5 · ChallengeThe total that isn't a number

          Ravi wants the total of all the stars. The console prints Total stars: NaN. Fix it. What does it print once fixed?

          <link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-rating value="4"></wa-rating><wa-rating value="5"></wa-rating><wa-rating value="3"></wa-rating> <script type="module">  let total = 0;  for (const rating of document.querySelectorAll("wa-rating")) {    total += rating.value;  }  console.log("Total stars:", total);</script>
          ResultLoading…

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

            Exercise 6 · ChallengeStop all three

            Make Stop logging remove all three listeners with one call. Which call is it?

            <link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css"><script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script> <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog><wa-button data-dialog="open guide">Brewing guide</wa-button><wa-button id="stop">Stop logging</wa-button> <script type="module">  const dialog = document.querySelector("wa-dialog");  dialog.addEventListener("wa-show", () => console.log("Opening"));  dialog.addEventListener("wa-after-show", () => console.log("Open"));  dialog.addEventListener("wa-hide", () => console.log("Closing"));  document.querySelector("#stop").addEventListener("click", () => {    // Stop all three listeners here  });</script>
            ResultLoading…

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

              Check your understanding

              For each question, ask which way the message goes: in through an attribute, property, or method, or out as an event.

              The talking to components quiz · 8 questionsScore: first tries count
              1. Question 1 of 8A page has <wa-rating value="4">. What does rating.getAttribute("value") give back?

                Choose an answer to see the explanation.

              2. Question 2 of 8What does line 4 of this code print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const card = document.createElement("div");
                const order = { tea: "Green tea", cups: 2 };
                card.setAttribute("data-order", order);
                console.log(card.getAttribute("data-order"));
                card.order = order;
                console.log(card.order.cups);

                Choose an answer to see the explanation.

              3. Question 3 of 8In the HTML, the dialog's attribute is light-dismiss. Which line turns it on from JavaScript?

                Choose an answer to see the explanation.

              4. Question 4 of 8You open this guide, close it, and open it again. What does the console print?

                Read the code, then predictPop out in the code editor (opens in a new tab)HTML
                <link rel="stylesheet" href="https://ka-f.webawesome.com/webawesome@3.15.0/styles/webawesome.css">
                <script type="module" src="https://ka-f.webawesome.com/webawesome@3.15.0/webawesome.loader.js"></script>
                
                <wa-dialog id="guide" label="Brewing guide">Use water at 80 degrees.</wa-dialog>
                <wa-button data-dialog="open guide">Brewing guide</wa-button>
                
                <script type="module">
                  const dialog = document.querySelector("wa-dialog");
                  dialog.addEventListener("wa-show", () => console.log("A"), { once: true });
                  dialog.addEventListener("wa-show", () => console.log("B"));
                </script>

                Choose an answer to see the explanation.

              5. Question 5 of 8A page listens for close on a wa-dialog, and the listener never runs. Why?

                Choose an answer to see the explanation.

              6. Question 6 of 8What does await customElements.whenDefined("wa-rating") give back?

                Choose an answer to see the explanation.

              7. Question 7 of 8A script runs before Web Awesome's files arrive and calls details.show(). What happens?

                Choose an answer to see the explanation.

              8. Question 8 of 8A listener on document hears wa-show from a wa-details inside <tea-guide>'s shadow root. What is event.target?

                Choose an answer to see the explanation.

              Key takeaways

              • You talk to a web component like any element: attributes, properties, methods, and events.
              • An attribute is always text in the HTML. A property is any value on the element. Objects, lists, and functions go in properties.
              • Attribute names are lowercase with hyphens, like light-dismiss. Property names are camelCase, like lightDismiss.
              • Call only the methods the docs list. Some, like details.show(), give back a promise you can await.
              • Listen for the exact event name, like wa-hide. Data lives in event.detail. Use once and an AbortController to stop listening.
              • Events that bubble and are composed reach the whole page. Outside a shadow root, the target is the host.
              • Before a class arrives, methods are missing. await customElements.whenDefined() waits, and gives you the class.

              Remember the one-liner.
              Settings go in as attributes and properties, requests as method calls, and news comes out as events, once the class has arrived.

              Sources

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

              Coming next: Theming components from the outside. Change a component's colors, sizes, and fonts with custom properties and CSS parts.

              CompleteFrontend Clear concepts. Working examples.