Skip to content

Custom HTML elements

You can always create your own custom HTML elements and then use them alongside built-in ones, e.g.:

<button>Hello world</button>

You can read more about this in this person’s blog post.

Here’s a simple component that extends HTMLElement:

class AstroGreet extends HTMLElement {
constructor() {
const button = this.querySelector("button")
button.addEventListener("click", () => {
alert("Hello world")
customElements.define("astro-greet", AstroGreet)

Then, to use the new astro-greet element, you could do something like this:

<button>Say hi!</button>

Suppose you have this:

<astro-greet data-message={message}>
<button id="test">Button 1</button>
<astro-greet data-message={message}>
<button id="test">Button 2</button>

…each AstroGreet can find its own local button with this.querySelector("#test"). However, in the resulting HTML, both buttons will have exactly the same ID.