JavaScript DOM

What is the DOM?

The DOM (Document Object Model) is the browser’s representation of an HTML page as a tree of objects. Every element, attribute, and piece of text becomes a node in that tree.

JavaScript can read and change that tree, which is what makes pages interactive: showing and hiding elements, updating text, responding to clicks, loading data without a full page reload.

console.dir(document); // explore the full document object

The document object

The document object is your entry point to the DOM. A few useful properties:

console.log(document.title);   // page title
console.log(document.URL);     // current URL
console.log(document.domain);  // e.g. "devhandbook.com"

What this section covers

  • DOM Selection : how to find elements by id, class, tag, or CSS selector
  • DOM Navigation : moving between parent, child, and sibling nodes
  • DOM Manipulation : creating, inserting, replacing, and removing elements
  • EventListener : adding and removing event listeners, event delegation
  • event.target : reading event properties to know what was clicked or typed

A simple example

<button id="greet-btn">Say hello</button>
<p id="message"></p>
const button = document.querySelector("#greet-btn");
const message = document.querySelector("#message");

button.addEventListener("click", () => {
  message.textContent = "Hello!";
});

When the button is clicked, the paragraph text updates. That is the DOM in action.