DOM Type Definitions
In this page:
Document Type
The Document type describes the single document object every page has access to, including its methods for querying and creating elements, and comes built into TypeScript's DOM library without any extra install.
Example: Document Type
const heading: HTMLElement = document.createElement("h1");
heading.textContent = "Hello";
console.log(heading.tagName);
HTMLElement Type
HTMLElement is the general base type for any element in the DOM tree, exposing shared properties like style, className, and addEventListener that every kind of element has in common.
Example: HTMLElement Type
const el: HTMLElement = document.createElement("div");
el.className = "box";
el.style.color = "blue";
console.log(el.className, el.style.color);
Specific Element Types
More specific element types like HTMLInputElement or HTMLButtonElement extend HTMLElement with properties unique to that tag, such as .value on inputs, so casting to the right specific type unlocks the right specific properties.
Example: Specific Element Types
const input: HTMLInputElement = document.createElement("input");
input.value = "hello";
console.log(input.value);
DOM Collections
DOM collection types like NodeList and HTMLCollection represent groups of elements returned by methods like querySelectorAll, and they differ slightly in whether they're live-updating and which array methods they support directly.
Example: DOM Collections
const container = document.createElement("div");
container.innerHTML = "<p>One</p><p>Two</p>";
const paragraphs: NodeListOf<HTMLParagraphElement> = container.querySelectorAll("p");
console.log(paragraphs.length);
Why DOM Types Matter
Using the correct DOM types instead of any means the compiler catches mistakes like reading .value on an element that isn't actually an input, well before that bug would otherwise surface as a runtime crash in the browser.
Example: Why DOM Types Matter
const input: HTMLInputElement = document.createElement("input");
input.value = "42";
// input.value is known to be a string, caught at compile time
console.log(input.value.length);
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: