Skip to main content
Practice Problems

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

  1. Node Tree:

The DOM represents a document as a tree of nodes, where each node corresponds to an element, attribute, or text. 2. Dynamic Updates:

The DOM allows you to change the content and structure of a document without reloading the page. 3. Interface for JavaScript:

Using the DOM API, you can modify page elements, their styles, add or remove elements.


Example of a DOM Tree

HTML:

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:

html
<h1 id="title">Welcome</h1> <button id="changeText">Change Text</button>

JavaScript:

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.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems