Search code examples
javascripthtmlcssregistrationcustom-element

What's the difference between an unregistered HTML Custom Element and a registered HTML Custom Element?


If I fail to register a custom element, I note that I can still:

  • style the unregistered element using CSS
  • add events to the unregistered element etc. using JS

Example:

// REGISTER <my-custom-element-1>
class MyRegisteredCustomElement1 extends HTMLElement {
  constructor() {
    super();
  }
};

customElements.define('my-custom-element-1', MyRegisteredCustomElement1);

// ATTACH EVENT LISTENERS TO BOTH CUSTOM ELEMENTS
const myCustomElement1 = document.getElementsByTagName('my-custom-element-1')[0];
const myCustomElement2 = document.getElementsByTagName('my-custom-element-2')[0];

const customElementAlert = (e) => {

  switch (e.target.nodeName.toLowerCase()) {
  
    case ('my-custom-element-1') : console.log('I\'m a registered custom element and I can be scripted and styled.'); break;
    case ('my-custom-element-2') : console.log('I\'m an unregistered custom element. Nevertheless, I can be scripted and styled TOO.'); break;
  }
}

myCustomElement1.addEventListener('click', customElementAlert, false);
myCustomElement2.addEventListener('click', customElementAlert, false);
:not(:defined) {
  border: 1px dashed rgb(0, 0, 0);
}

my-custom-element-1,
my-custom-element-2 {
  float: left;
  display: inline-block;
  width: 100px;
  height: 100px;
  margin-right: 12px;
  padding: 6px;
  text-align: center;
  font-weight: bold;
  cursor: pointer;
}

my-custom-element-1 {
  color: rgb(255, 255, 255);
  background-color: rgb(255, 0, 0);
}

my-custom-element-1::after {
  content: 'I\'m a registered custom element.\A CLICK ME';
}

my-custom-element-2 {
  background-color: rgb(255, 255, 0);
}

my-custom-element-2::after {
  content: 'I\'m an unregistered custom element.\A CLICK ME';
}
<my-custom-element-1></my-custom-element-1>
<my-custom-element-2></my-custom-element-2>

If unregistered custom elements may be styled and scripted, what is it, specifically, that registering a custom element enables?


Solution

  • Basically it associates the element with the class you set for it. It:

    • allows using lifecycle callbacks like connectedCallback (and disconnectedCallback)
    • allows for custom logic and properties in the constructor.

    The my-custom-element-2 element you've created is just a regular HTML element without the specific class you gave it. If you inspect the DOM you'll see the class of my-custom-element-2 is HTMLElement whereas the class of my-custom-element-1 is myRegisteredCustomElement1.