JavaScript DOM
The Document Object Model (DOM) is an essential concept. Without it, JavaScript couldn't change a webpage. The DOM bridges your JS code to the HTML document by representing the page as an Object Tree.
The Tree of Nodes
When a web browser loads an HTML file, it parses it and creates a model of it in memory. In this tree, the entire document is the root node. Every HTML tag is an element node, and the text inside them are text nodes.
JavaScript uses the global document object to query this tree.
Selecting Elements
Before you can change something, you have to point at it. We have multiple tools in our belt:
document.getElementById("my-id")- Fast and specific. Returns one element.document.querySelector(".my-class")- Versatile. Uses CSS syntax. Returns the first match.document.querySelectorAll("p")- Returns a NodeList of all matching elements.
Manipulating Elements
Once selected, the element behaves like a standard JavaScript object. You can access and mutate its properties:
title.textContent = 'New Title Here!';
title.style.color = 'blue';
title.classList.add('highlight');
Notice that you can change the text content, inject inline styles, or manipulate CSS classes using the classList API, which is often much cleaner than changing inline styles!
View Deep Dive on Node Creation+
To add elements dynamically, you use document.createElement("tagName"). This creates a "detached" node that exists in JS memory but not on the screen.
Once you set its attributes (like textContent or classes), you must attach it to an existing DOM node using methods like parent.appendChild(newNode) or parent.insertBefore(newNode, sibling).
