WebDev Bites: HTML DOM

DOM JavaScript API and example

Figure 1 - HTML DOM

1.0 - HTML DOM API

The HTML Document Object Model (DOM) is a tree of nodes, most of which are elements, that define how content is rendered on the web page. The Application Programming Interface (API) exposes the HTML DOM for JavaScript search, creation, and mutation. The API consists of methods and properties that are defined on the global document object, accessible to all JavaScript code. JavaScript can create web-worker threads, but only the primary JavaScript thread is allowed to access the HTML document. For reasons of performance, the DOM provides no locking mechanisms that would support multi-threaded access. We will see in the JavaScript byte that its execution engine is designed to repond to events and, as long as each event handler is brief, performance is surprisingly good. Table 1. contains methods and properties most frequently used in JavaScript code to respond to user events and modify document content at run-time.

Table 1. - Frequently used DOM API Methods and Properties

Method / Property Description Example
document.getElementById(id) Returns the element with the given id. let el = document.getElementById("header");
document.querySelector(sel) Returns the first element matching a CSS selector. let btn = document.querySelector(".btn");
document.querySelectorAll(sel) Returns all elements matching a CSS selector. let items = document.querySelectorAll("li");
element.addEventListener(type, fn) Attaches an event handler to an element. btn.addEventListener("click", doStuff);
document.createElement(tag) Creates a new element node. let div = document.createElement("div");
parent.appendChild(node) Adds a node to the end of a parent element. div.appendChild(span);
element.remove() Removes the element from the DOM. el.remove();
element.setAttribute(name, value) Sets the value of an attribute. el.setAttribute("class","active");
element.getAttribute(name) Gets the value of an attribute. let c = el.getAttribute("class");
element.classList.add(name) Adds a class to the element. el.classList.add("highlight");
element.classList.remove(name) Removes a class from the element. el.classList.remove("hidden");
element.innerHTML Gets/sets the HTML markup inside an element. el.innerHTML = "<p>Hi</p>";
element.textContent Gets/sets plain text inside an element. el.textContent = "Hello";

2. - Node Traversal

DOM nodes are the most general type of object in the DOM tree.
DOM Tree Node Navigation

Table 2. - Node properties used for DOM tree navigation.

Property Description Example
node.parentNode Returns the parent node of the element. let parent = el.parentNode;
node.childNodes Returns all child nodes (including text/comment nodes). let kids = el.childNodes;
node.children Returns only child elements (no text/comment). let elems = el.children;
node.firstChild Returns the first child node. let first = el.firstChild;
node.lastChild Returns the last child node. let last = el.lastChild;
node.firstElementChild Returns the first child element. let firstEl = el.firstElementChild;
node.lastElementChild Returns the last child element. let lastEl = el.lastElementChild;
node.nextSibling Returns the next sibling node (may be text). let sib = el.nextSibling;
node.previousSibling Returns the previous sibling node (may be text). let prev = el.previousSibling;
node.nextElementSibling Returns the next sibling element. let sibEl = el.nextElementSibling;
node.previousElementSibling Returns the previous sibling element. let prevEl = el.previousElementSibling;

3. - Document Element Traversal

Elements are the unit of HTML page structure. They define the placement of visual objects on each web page. Their attributes are hooks for styling and modes of placement.
<div style="position:fixed; top:5rem; left:3rem; background-color: var(--light);>
  element fixed near top left of Page 
</div>
The HTML element type derives from base node type. So, its interface provides element-specific methods and properties to the node methods and properties.
Document Element Relationships

Table 3. - DOM Element Relationships

Method Description Example
element.closest(selector) Finds the nearest ancestor (including self) that matches a CSS selector. let form = btn.closest("form");
element.matches(selector) Checks if the element matches a CSS selector. if (el.matches(".active")) {...}
node.contains(other) Returns true if the node contains the other node. if (div.contains(span)) {...}
element.hasChildNodes() Returns true if the node has any children. if (el.hasChildNodes()) {...}
element.getRootNode() Returns the root node (document or shadow root). let root = el.getRootNode();
element.closest(":root") Alternative way to reach the document root using selectors. let root = el.closest(":root");
element.querySelectorAll(sel) Scoped search for all matching descendants. let links = nav.querySelectorAll("a");

4.0 - References

Reference: Large Selection of DOM API Methods

Table 4. - Selection of most commonly used DOM API Methods

Category Key Methods / Properties Description Example
Node appendChild
removeChild
replaceChild
cloneNode
normalize
Base of DOM tree. Core manipulation of nodes (adding/removing/cloning) and normalization. const p = document.createElement('p');
document.body.appendChild(p);
Element getAttribute / setAttribute / removeAttribute / hasAttribute
querySelector / querySelectorAll
closest / matches
Represents element nodes; attribute access, querying descendants, selector matching, and traversal. const el = document.querySelector('.item');
if (el.matches('.active')) { /*...*/ }
HTMLElement focus() / blur() / click()
scrollIntoView()
getBoundingClientRect()
dataset
insertAdjacentHTML / insertAdjacentElement
HTML-specific element features: focus control, geometry, data-* access, and convenient insertion. el.dataset.id = '42';
el.scrollIntoView();
Document createElement
createTextNode
getElementById
querySelectorAll
body / head / documentElement
Root of DOM; create nodes, access top-level elements, and perform global queries. const div = document.createElement('div');
document.body.appendChild(div);
EventTarget addEventListener
removeEventListener
dispatchEvent
Event handling mechanism used by nodes: subscribe, unsubscribe, and emit events. el.addEventListener('click', e => console.log(e));
el.dispatchEvent(new Event('custom'));
Tree traversal / manipulation parentNode / children / childNodes
nextSibling / previousSibling
replaceWith / remove / prepend / append
Navigate and modify the DOM structure, including inserting and replacing elements. el.replaceWith(document.createElement('span'));
Selectors querySelector / querySelectorAll
getElementById / getElementsByClassName / getElementsByTagName
Find elements using CSS selectors or legacy collection methods (some live). const items = document.getElementsByClassName('card');
Attributes vs Properties setAttribute / getAttribute
property access (e.g., el.value)
dataset
Attributes are markup; properties are JS object fields. Reflection patterns sync them. el.setAttribute('data-role','admin');
console.log(el.dataset.role);
Events new Event / MouseEvent / CustomEvent
event.preventDefault()
event.stopPropagation()
Creation, dispatch, and handling of events. Supports bubbling, capturing, and delegation. el.addEventListener('submit', e => { e.preventDefault(); });
Shadow DOM attachShadow({mode})
<slot>
Encapsulation of markup/styles; slotting projects light DOM content into shadow DOM. const root = el.attachShadow({mode:'open'});
root.innerHTML = '<slot></slot>';
Custom Elements class X extends HTMLElement
customElements.define(name, constructor)
connectedCallback / disconnectedCallback / attributeChangedCallback / adoptedCallback
Define new HTML tags with lifecycle hooks and encapsulated behavior. customElements.define('my-widget', MyWidget);
MutationObserver new MutationObserver(callback)
observe(target, options)
Watch DOM changes (child list, attributes, subtree) and react programmatically. const obs = new MutationObserver(m => console.log(m));
obs.observe(el, { childList: true });
Geometry / Layout getBoundingClientRect()
window.getComputedStyle()
Measure element size/position and computed styles, essential for layout logic. const rect = el.getBoundingClientRect();
Class / Data helpers classList (add/toggle/contains/remove)
dataset
Utility accessors for manipulating CSS classes and data-* attributes easily. el.classList.toggle('active');
Templates <template>
template.content.cloneNode(true)
Define inert HTML fragments to instantiate multiple times without executing scripts. const tpl = document.getElementById('tpl');
document.body.appendChild(tpl.content.cloneNode(true));
DocumentFragment createDocumentFragment() Batch DOM insertions efficiently; fragment isn't rendered until appended. const frag = document.createDocumentFragment();
frag.appendChild(document.createElement('div'));
document.body.appendChild(frag);
CustomEvent new CustomEvent(type, { detail }) Dispatch events with structured payloads. el.dispatchEvent(new CustomEvent('update', { detail: { id: 5 } }));