The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page as a tree of objects so that JavaScript can dynamically change the document’s structure, style, and content without reloading the page.
document object lets you read and modify that tree.id, class, src.The DOM is exposed to JavaScript through the global document object. You use its methods to find and work with elements:
document.getElementById("id") – select a single element by its id.document.getElementsByClassName("class") – get a live HTMLCollection of elements.document.getElementsByTagName("tag") – get all elements with a given tag name.document.querySelector("selector") – get the first element matching a CSS selector.document.querySelectorAll("selector") – get a static NodeList of all matches.Each DOM node has useful properties and methods, for example:
node.nodeName – the name of the node (like DIV).node.nodeType – the type of node (1 = element, 3 = text, etc.).node.childNodes – a list of a node’s children.node.firstChild – the first child node.element.textContent – the text inside an element.Use different DOM methods to select elements by id, class, or tag name:
// Access element by ID
const heading = document.getElementById("myHeading");
console.log(heading.textContent);
// Access elements by class name
const items = document.getElementsByClassName("list-item");
console.log(items.length);
// Access elements by tag name
const paragraphs = document.getElementsByTagName("p");
console.log(paragraphs[0].textContent);
Every element node exposes properties that describe its type and children:
const element = document.querySelector("div");
console.log(element.nodeName); // DIV
console.log(element.nodeType); // 1 (Element Node)
console.log(element.childNodes); // NodeList of child nodes
console.log(element.firstChild); // First child node (could be text or element)
You can change the text inside an element using textContent:
<h2 id="title">Old Title</h2>
<script>
const title = document.getElementById("title");
title.textContent = "New Title";
</script>
Click the button to see how JavaScript updates the DOM without reloading the page.
This text was set when the page loaded.
nodeName and nodeType show what kind of node you selected, and childNodes reveals the node’s children.textContent, showing how the DOM lets you react to user actions.document.getElementById() for selecting a single, unique element by its ID.document.querySelector() and document.querySelectorAll() for flexible CSS selector queries.textContent when inserting plain text to avoid security issues with HTML injection.textContent.getElementById, getElementsByClassName, and querySelector to select different elements and log them in the console.nodeName, nodeType, and childNodes.createElement and appendChild.