HTML - Custom Tag / Element

1 - About

custom is the possibility create custom element

By adding them in a shadow DOM (to scope the DOM selection) and using templates element, you are creating web components

3 - Example

3.1 - words-count

Taken from custom element where we will count word.

  • An HTML text area to change the number of words.

<textarea cols=40 rows=4>Word Count example</textarea>

  • The HTML with a custom element defined with the is attribute. The 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 and in a new sub dom (shadow)

// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();

    // count words in element's parent element
    const wcParent = this.previousElementSibling;

    function countWords(node){
      const text = node.value || 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
    shadow.appendChild(text);

    // Update count at interval
    setInterval(function() {
      debugger;
      const count = `Words: ${countWords(wcParent)}`;
      text.textContent = count;
    }, 5000);
  }
}

// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });

  • The result

4 - Documentation / Reference


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap