Creating custom HTML elements with Javascript

Kelvin Wangonya - Mar 22 '19 - - Dev Community

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(
  "initially-hidden",
  class extends HTMLElement {
    createdCallback() {
      this.revealTimeoutId = null;
    }
    attachedCallback() {
      const seconds = Number(this.getAttribute("for"));
      this.style.display = "none";
      this.revealTimeoutId = setTimeout(() => {
        this.style.display = "block";
      }, seconds * 1000);
    }
    detachedCallback() {
      if (this.revealTimeoutId) {
        clearTimeout(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?

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .