A small piece of HTML can change what a visitor sees or how the browser understands a page. In this lesson, you will explore web components exercise: build an accessible custom card using a short example that you can inspect and change.
The Idea in Plain English
A custom element is a reusable browser component whose name must include a hyphen. Its behavior comes from JavaScript registration, not just from writing an unknown tag.
Treat this as a practical project: start with a working page, check one requirement at a time, and use the browser inspector to verify the finished result.
A Working Example
Read the sample once before copying it. Notice the element names and attribute values, then compare them with the explanation below.
<study-note>Remember to practice.</study-note>
<script>
class StudyNote extends HTMLElement {
connectedCallback() {
this.setAttribute("role", "note");
}
}
customElements.define("study-note", StudyNote);
</script>
What Each Part Does
- The script element can load code or hold data; the type attribute tells the browser how to treat its contents.
- The browser reads these lines in order and uses them to build the page or request.
- Changing the relevant value lets you test what this feature controls.
Before registration the tag is just an unknown element; after a definition is registered it can upgrade into a custom element.
Keep the example small while learning. Once it behaves as expected, try it inside a larger page and make sure the URLs, files and surrounding HTML are correct.
Try It Yourself
Try this next: create a custom card used twice on one page. Then inspect the page and explain what changed.
Common Beginner Mistakes
- Expecting <my-card> to behave like a complete component without a matching customElements.define call.
- Changing several parts of the example at once, making it difficult to see which part caused a different result.
- Choosing a tag only because its default appearance looks right, without checking whether it describes the content correctly.
Key Takeaways
- A custom element is a reusable browser component whose name must include a hyphen. Its behavior comes from JavaScript registration, not just from writing an unknown tag.
- Before registration the tag is just an unknown element; after a definition is registered it can upgrade into a custom element.
- Test the markup in a browser, and check accessibility and real-world behavior where relevant.