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.:

<my-custom-element>
<button>Hello world</button>
</my-custom-element>

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() {
super()
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:

<astro-greet>
<button>Say hi!</button>
</astro-greet>

Suppose you have this:

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

…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.