liveBook · Manning

HTMLElement API

As explained in Web Component Development with Modern Libraries and Tooling

The browser-provided JavaScript base class for HTML elements.

HTMLElement is the browser-provided DOM base class for custom HTML elements. Extend it with a JavaScript class, then register that class under a custom element name. section 1.3 section 3.1

A minimal HTMLElement-based component follows these rules:

  • Extend HTMLElement or a subclass of it. section 3.1.1
  • Register the class with customElements.define and a lowercase name containing at least one hyphen. section 3.1 section 3.1.1
  • Use an explicit closing tag because custom elements cannot be self-closing. section 3.1
  • Avoid duplicate registrations by checking customElements.get before defining a name. section 3.1.1

A greeting component

class HelloWorld extends HTMLElement { connectedCallback() { const name = this.getAttribute("name") ?? "World"; this.innerHTML = `<p>Hello, ${name}!</p>`; } } customElements.define("hello-world", HelloWorld); Use it as <hello-world></hello-world> or <hello-world name="Mark"></hello-world>. A component can also attach a shadow root, place HTML and CSS inside it, and respond to events such as clicks. section 1.3 section 3.1.1

Figure 1.2 illustrates how a web component encapsulates HTML, CSS, and JavaScript within a single JavaScript class that extends HTMLElement. The class defines the component’s lifecycle and behavior, specifies its HTML markup, and applies CSS to control its appearance in a way that’s scoped to the component.
essential parts of a web component

Shows how one HTMLElement subclass combines component lifecycle, HTML markup, JavaScript behavior, and scoped CSS. section 1.3

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains inheritance, lifecycle usage, registration, naming constraints, duplicate checks, and basic browser errors.
Examples
Uses a hello-world greeting component with an optional name attribute, paragraph output, a button, scoped styling, and click behavior.
What it assumes
Assumes basic HTML and JavaScript familiarity while introducing the DOM, custom element naming, and browser registration behavior.
What you can do after
Build it from scratch by extending HTMLElement, implementing connectedCallback, registering a valid name, and using the resulting custom element.
How it connects
Connects HTMLElement with the DOM, custom elements, Custom Elements specification, shadow DOM, HTML, CSS, and JavaScript.

Also explained in

Compare how 3 books explain HTMLElement API →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.