Skip to content

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

javascript

Register a custom element class.

class HelloWorld extends HTMLElement {
  connectedCallback() {
    this.textContent = "Hello";
  }
}
customElements.define("hello-world", HelloWorld);

2. Attach Shadow Root

javascript

Attach an open shadow root.

class Card extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
  }
}

3. Observed Attributes

javascript

React to attribute changes.

static get observedAttributes() {
  return ["label"];
}
attributeChangedCallback(name, _old, value) {
  if (name === "label") this.render(value);
}

4. Slot Content

html

Render a named slot in shadow DOM.

<slot name="title"></slot>
<slot></slot>

5. Custom Event

javascript

Dispatch a composed custom event.

this.dispatchEvent(
  new CustomEvent("save", { detail: { id: 1 }, bubbles: true, composed: true })
);

6. CSS Parts

html

Expose a part for external styling.

<button part="trigger">Open</button>

7. Form Associated

javascript

Mark an element as form-associated.

class FancyInput extends HTMLElement {
  static formAssociated = true;
  constructor() {
    super();
    this._internals = this.attachInternals();
  }
}

8. Adopted Stylesheets

javascript

Apply a Constructable Stylesheet.

const sheet = new CSSStyleSheet();
sheet.replaceSync(":host { display: block; }");
this.shadowRoot.adoptedStyleSheets = [sheet];

9. Disconnected Cleanup

javascript

Clean up listeners on disconnect.

disconnectedCallback() {
  this.button?.removeEventListener("click", this.onClick);
}

10. Template Clone

javascript

Clone a template into shadow root.

const template = document.getElementById("card-tpl");
this.shadowRoot.append(template.content.cloneNode(true));