Hemanth's Scribes

web

Custom Elements with ES6

Author Photo

Hemanth HM

Thumbnail

Custom Elements are key to Web Components:

  • Define new DOM elements
  • Extending from other elements
  • Extending DOM APIs
  • Providing custom functionality to a single tag

ES6 Class Boilerplate

class CustomElement extends HTMLElement {
  // Fires when an instance is created
  createdCallback() {}
  
  // Fires when inserted into the document
  attachedCallback() {}
  
  // Fires when removed from the document
  detachedCallback() {}
  
  // Fires when an attribute changes
  attributeChangedCallback(attr, oldVal, newVal) {}
}

document.registerElement('custom-element', CustomElement);

## Extending HTMLSpanElement
javascript
class DateSpan extends HTMLSpanElement {
  createdCallback() {
    this.textContent = "Today's date: " + new Date().toJSON().slice(0, 10);
  }
}

document.registerElement('date-today', DateSpan);
#web#webcomponents#es6
Author Photo

About Hemanth HM

Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.