What is the DOM?
DOM (Document Object Model) is a programming interface that represents the structure of HTML or XML documents as a tree of objects. The DOM allows JavaScript to interact with web page content, modify its structure, style, and behavior.
Key Features of the DOM
-
Node Tree:
The DOM represents a document as a tree of nodes, where each node corresponds to an element, attribute, or text. -
Dynamic Updates:
The DOM allows you to change the content and structure of a document without reloading the page. -
Interface for JavaScript:
Using the DOM API, you can modify page elements, their styles, add or remove elements.
Example of a DOM Tree
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Example</title>
</head>
<body>
<h1>Hello, DOM!</h1>
<p>This is an example.</p>
</body>
</html>
Working with the DOM
Here's an example of how to use the DOM API to change page content.
HTML:
<h1 id="title">Welcome</h1>
<button id="changeText">Change Text</button>
JavaScript:
// Get the heading element and button
const title = document.getElementById("title");
const button = document.getElementById("changeText");
// Add click handler
button.addEventListener("click", () => {
title.textContent = "Text changed!";
});
Main DOM Methods
document.getElementById(id)— get element by ID.document.querySelector(selector)— get the first element matching the CSS selector.document.querySelectorAll(selector)— get all elements matching the CSS selector.element.textContent— change the text of an element.element.innerHTML— change the HTML content of an element.element.style— change element styles.
Tip:
The DOM API is a powerful tool, but for complex tasks, use modern libraries like React to simplify interface work.