DEV Community

loading...
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(
  "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?

Discussion (2)

Collapse
kozakrisz profile image
Krisztian Kecskes

I mixed them with Redux:
github.com/krisztiankecskes/counte...

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