The Document Object Model (DOM) is the live tree of objects a browser builds when it parses an HTML page. JavaScript uses the global document object to read, create, update, and remove HTML elements, attributes, and styles on the fly.
Every piece of HTML becomes a node inside a parent-child hierarchy starting at document. Element tags like <body>, <main>, and <p> are Element nodes, while the words inside <p> are Text nodes.
flowchart TD
Doc["document"] --> Html["html element"]
Html --> Head["head element"]
Html --> Body["body element"]
Head --> Title["title element"]
Body --> Header["header element"]
Body --> Main["main element"]
Main --> Para["p element"]
Para --> Text["Hello DOM text node"]
Understanding the difference between a general Node and an Element prevents subtle counting bugs:
nodeType === 1): Represents HTML tags like <div>, <button>, and <ul>. Properties like .children return Element nodes only.nodeType === 3): Represents text content, including line breaks and spaces between tags! .childNodes includes both Elements and whitespace Text nodes.// Create a small DOM subtree and inspect nodes vs elements
const card = document.createElement("div");
card.innerHTML = "
<p>Welcome to the DOM</p>
";
console.log("Document title:", document.title);
console.log("card.nodeType (Element=1):", card.nodeType);
console.log("childNodes (includes whitespace text):", card.childNodes.length);
console.log("children (HTML elements only):", card.children.length);
<head> without defer run before <body> exists, returning null. Always use defer or wrap setup in DOMContentLoaded.childNodes expecting only tags: Line breaks in HTML create extra Text nodes inside childNodes. Use element.children for element tags.No, the DOM is a browser Web API standardized by the W3C and WHATWG. Node.js does not include a browser DOM unless you install a library like jsdom.
document and window?window represents the browser tab and global environment (setTimeout, location, localStorage), while window.document represents the loaded web page inside that tab.
Every DOM insertion can trigger browser style recalculation and layout reflow. Build nodes inside a DocumentFragment first, then attach once.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.