DOM

Read and update HTML elements from JavaScript.

DOM Manipulation is one of the most exciting parts of JavaScript because it allows you to interact with and change web pages dynamically. You can update text, modify styles, create new elements, remove content, and respond to user actions without reloading the page.

What Is the DOM?

DOM stands for Document Object Model. When a browser loads an HTML page, it creates a structured representation of that page called the DOM.

html
<h1 id="title">Welcome</h1>
<p>This is a website.</p>

Think of the DOM as a bridge between JavaScript and HTML.

Why Is DOM Manipulation Important?

  • Change webpage content dynamically.
  • Update styles and layouts.
  • Show or hide elements.
  • Create interactive user experiences.
  • Respond to user actions.

Selecting Elements

Selecting by ID

javascript
let heading = document.getElementById("title");

Using querySelector()

javascript
let heading = document.querySelector("#title");

Changing Content

javascript
let heading = document.getElementById("title");

heading.textContent = "Hello JavaScript!";

Before

html
<h1>Welcome</h1>

After

html
<h1>Hello JavaScript!</h1>

Changing Styles

javascript
let heading = document.getElementById("title");

heading.style.color = "blue";
heading.style.fontSize = "40px";

Creating New Elements

javascript
let paragraph = document.createElement("p");

paragraph.textContent = "This paragraph was created with JavaScript.";

document.body.appendChild(paragraph);

Removing Elements

javascript
let heading = document.getElementById("title");

heading.remove();

Real-World Example

HTML

html
<h1 id="message">Welcome!</h1>

<button onclick="changeText()">Click Me</button>

JavaScript

javascript
function changeText() {
    document.getElementById("message").textContent =
        "Thanks for clicking!";
}

Common DOM Methods

  • getElementById(): select an element by ID
  • querySelector(): select the first matching element
  • querySelectorAll(): select multiple elements
  • createElement(): create a new element
  • appendChild(): add an element
  • remove(): remove an element

Summary

DOM Manipulation allows JavaScript to interact with HTML elements and update webpages dynamically. Selecting elements, changing content, modifying styles, creating elements, and removing elements form the foundation of modern front-end development.

Let's learn with DevBrainBox AI