DEV Community

Cover image for Creating custom HTML elements with Javascript

Creating custom HTML elements with Javascript

Kinyanjui Wangonya
・1 min read

I just learned today that it's possible to create custom HTML elements with Javascript and extend existing ones. Here's an example:

const InitiallyHiddenElement = document.registerElement(
  class extends HTMLElement {
    createdCallback() {
      this.revealTimeoutId = null;
    attachedCallback() {
      const seconds = Number(this.getAttribute("for")); = "none";
      this.revealTimeoutId = setTimeout(() => { = "block";
      }, seconds * 1000);
    detachedCallback() {
      if (this.revealTimeoutId) {
        this.revealTimeoutId = null;
Enter fullscreen mode Exit fullscreen mode

Running <initially-hidden for="2">Hello</initially-hidden> & <initially-hidden for="5">World</initially-hidden> on the webpage would delay the elements from appearing for 2 seconds and 5 seconds respectively.

This idea seems pretty cool but I'm just thinking: all this can still be done in JS and CSS without having to create the custom element.

What would be some good use-cases where creating custom elements would be a better way to go?

Discussion (2)

kozakrisz profile image
Krisztian Kecskes

I mixed them with Redux:

mvasigh profile image
Mehdi Vasigh • Edited

Read up on Web Components, lit-element and lit-html :) custom elements are a big part of the Web Components movement.