Coding practice
Web Components Coding Questions
10 hands-on challenges with prompts and solution sketches for Web Components interview rounds.
Challenge set
10 coding questions
1. Define Custom Element
javascriptRegister a custom element class.
class HelloWorld extends HTMLElement {
connectedCallback() {
this.textContent = "Hello";
}
}
customElements.define("hello-world", HelloWorld); 2. Attach Shadow Root
javascriptAttach an open shadow root.
class Card extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
}
} 3. Observed Attributes
javascriptReact to attribute changes.
static get observedAttributes() {
return ["label"];
}
attributeChangedCallback(name, _old, value) {
if (name === "label") this.render(value);
} 4. Slot Content
htmlRender a named slot in shadow DOM.
<slot name="title"></slot>
<slot></slot> 5. Custom Event
javascriptDispatch a composed custom event.
this.dispatchEvent(
new CustomEvent("save", { detail: { id: 1 }, bubbles: true, composed: true })
); 6. CSS Parts
htmlExpose a part for external styling.
<button part="trigger">Open</button> 7. Form Associated
javascriptMark an element as form-associated.
class FancyInput extends HTMLElement {
static formAssociated = true;
constructor() {
super();
this._internals = this.attachInternals();
}
} 8. Adopted Stylesheets
javascriptApply a Constructable Stylesheet.
const sheet = new CSSStyleSheet();
sheet.replaceSync(":host { display: block; }");
this.shadowRoot.adoptedStyleSheets = [sheet]; 9. Disconnected Cleanup
javascriptClean up listeners on disconnect.
disconnectedCallback() {
this.button?.removeEventListener("click", this.onClick);
} 10. Template Clone
javascriptClone a template into shadow root.
const template = document.getElementById("card-tpl");
this.shadowRoot.append(template.content.cloneNode(true));