<article contenteditable="true">
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Animi voluptatem consequatur veritatis architecto id illo itaque eos doloremque deleniti facilis esse, hic iusto aperiam possimus libero ex blanditiis. Ut, illo?</p>
<p is="word-count"></p>
</article>
body {
padding: 2rem;
}
article {
padding: 0.5rem 1rem;
border: 1px solid #ccc;
border-radius: 5px;
}
View Compiled
// 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
var wcParent = this.parentNode;
function countWords(node) {
var text = node.innerText || node.textContent;
return text.trim().split(/\s+/g).length;
}
var count = "Words: " + countWords(wcParent);
// Create a shadow root
var shadow = this.attachShadow({ mode: "closed" });
// Create text node and add word count to it
var text = document.createElement("span");
text.textContent = count;
// Append it to the shadow root
shadow.appendChild(text);
// Update count when element content changes
setInterval(function () {
var count = "Words: " + countWords(wcParent);
text.textContent = count;
}, 200);
}
}
// Define the new element
customElements.define("word-count", WordCount, { extends: "p" });
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.