Web - Component

> (World Wide) Web - (W3|WWW)

1 - About

Web Components are a set of features that provide a component model:

  • Custom Element – APIs to define new HTML elements
  • Shadow DOM – Encapsulated DOM and styling, with composition
  • HTML Templates, an HTML fragment is not rendered, but stored until it is instantiated via JavaScript[

At their most basic level, they are a way to package up styling and functionality into new, custom HTML tags that can be easily reused or shared with others.

2 - Example

2.1 - Custom Element

Taken from custom element where we will count word.

  • The HTML with a custom element defined with the is attribute
<p>Word Count example</p>
<!-- This custom element will count the words of the parent node -->
<p is="word-count"></p>
  • The definition of the custom element is in a class
// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    // count words in element's parent element
    const wcParent = this.parentNode;
    function countWords(node){
      const text = node.innerText || node.textContent;
      return text.split(/\s+/g).length;
    const count = `Words: ${countWords(wcParent)}`;
    // Create a shadow root
    const shadow = this.attachShadow({mode: 'open'});
    // Create text node and add word count to it
    const text = document.createElement('span');
    text.textContent = count;
    // Append it to the shadow root
    // Update count when element content changes
    setInterval(function() {
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count;
    }, 200);
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
  • The result


2.2 - Library

3 - Documentation / Reference