A custom element in JavaScript
Your own tag, with shadow DOM and lifecycle callbacks.
class StarRating extends HTMLElement {
static observedAttributes = ["stars"];
constructor() {
super();
this.attachShadow({ mode: "open" });
}
connectedCallback() {
this.render();
}
attributeChangedCallback(name, previous, next) {
if (previous !== next) this.render();
}
render() {
const stars = Number(this.getAttribute("stars") ?? 0);
this.shadowRoot.innerHTML = `
<style>:host { color: rebeccapurple; }</style>
<span>${"*".repeat(stars)}${".".repeat(3 - stars)}</span>
`;
}
}
customElements.define("star-rating", StarRating);
How it works
connectedCallbackruns when it enters the document.observedAttributesdrivesattributeChangedCallback.- Shadow DOM scopes the styles to the component.
Keywords and builtins used here
Numberclassconstconstructorextendsifstaticsuperthis
The run, in numbers
- Lines
- 26
- Characters to type
- 532
- Tokens
- 125
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 71 seconds.
Step 2 of 2 in Watching & drawing, step 10 of 13 in The browser.