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
Example: Words Count
HTML Element
count word analytics element.
- 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
<word-count/>
- 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 HTMLElement {
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('p');
text.textContent = count;
// Append it to the shadow root
shadow.appendChild(text);
// Update count at interval
setInterval(function() {
const count = `Words: ${countWords(wcParent)}`;
text.textContent = count;
}, 5000);
}
}
// Define the new element
customElements.define('word-count', WordCount);
- The result
Extends HTML Element
This example shows how to extends an actual HTML element. It 's the same previous count word example but that extends the p element
The difference with the previous example are:
- A custom element that extends an actual HTML element should be defined with the is attribute and not as element
<p is="word-count"></p>
- The definition of the custom element extends declaratively the HTMLParagraphElement and no more the HTMLElement
// Create a class for the element
class WordCount extends HTMLParagraphElement {
// ...
- When defining the new element, the extension should be declared in the extends option property.
customElements.define('word-count', WordCount, { extends: 'p' });
- The result
Ref: Taken from custom element