A custom element in HTML
A tag of your own, with its behavior attached to the tag rather than to a selector.
<word-count for="editor">0 words</word-count>
<textarea id="editor" rows="4"></textarea>
<script>
class WordCount extends HTMLElement {
connectedCallback() {
const target = document.getElementById(this.getAttribute('for'));
target.addEventListener('input', () => {
const words = target.value.trim().split(/\s+/).filter(Boolean);
this.textContent = `${words.length} words`;
});
}
}
customElements.define('word-count', WordCount);
</script>
How it works
- A custom element's name must contain a hyphen.
connectedCallbackruns when it enters the document.- Until the script defines it, it is an unknown inline element.
Keywords and builtins used here
Booleanclassconstdocumentextendsthis
The run, in numbers
- Lines
- 16
- Characters to type
- 440
- Tokens
- 113
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 85 seconds.
Step 2 of 3 in Templates & components, step 6 of 13 in Interactive HTML.