01 / 20
</>

Reading & Updating
the DOM

Learn to read text, attributes, and classes from HTML elements and update them dynamically with JavaScript.

JavaScript

What Is the DOM?

The Document Object Model (DOM) is a tree-like representation of your HTML page that JavaScript can interact with. Every HTML tag becomes a node in this tree, and JavaScript gives you methods to read and change each node.

document <html> <head> <body> <h1> <p> "Hello" "World"

Selecting Elements

Before you can read or update anything, you need a reference to the element. JavaScript provides several selector methods on the document object.

getElementById
Returns the single element with a matching id attribute.
querySelector
Returns the first element matching any CSS selector.
querySelectorAll
Returns a NodeList of all matching elements.
JavaScript
// By ID
const heading = document.getElementById("title");

// By CSS selector
const btn = document.querySelector(".btn-primary");

// All matching elements
const items = document.querySelectorAll("li");

The Three Pillars of DOM Updates

Once you have an element reference, there are three categories of things you can read and change:

Text
The visible words inside an element: textContent and innerHTML.
Attributes
Key-value pairs on the tag: src, href, id, data attributes.
Classes
The classList API to add, remove, and toggle CSS classes.

Reading & Updating Text

HTML
<p id="msg">Hello, world!</p>
JavaScript
const el = document.getElementById("msg");

// READ text
console.log(el.textContent);  // "Hello, world!"

// UPDATE text
el.textContent = "Goodbye, world!";

textContent vs innerHTML

textContent innerHTML
Returns Plain text only HTML markup string
Sets Escapes tags as text Parses tags as HTML
Performance Faster Slower (re-parse)
Security Safe XSS risk
Use when Displaying user input Inserting rich HTML

Reading & Updating Attributes

HTML
<img id="logo" src="cat.png" alt="A cat">
JavaScript
const img = document.getElementById("logo");

// READ an attribute
img.getAttribute("src");       // "cat.png"

// UPDATE an attribute
img.setAttribute("src", "dog.png");
img.setAttribute("alt", "A dog");

// REMOVE an attribute
img.removeAttribute("alt");

// CHECK if attribute exists
img.hasAttribute("alt");      // false

Reading & Updating Classes

JavaScript
const box = document.querySelector(".card");

// ADD a class
box.classList.add("active");

// REMOVE a class
box.classList.remove("hidden");

// TOGGLE: add if absent, remove if present
box.classList.toggle("highlight");

// CHECK if a class exists
box.classList.contains("active"); // true

The Core API at a Glance

Element Node Text .textContent .innerHTML .innerText Attributes .getAttribute() .setAttribute() .removeAttribute() Classes .classList.add() .classList.remove() .classList.toggle() .classList.contains()

Step-by-Step Workflow

1
Select the element using getElementById or querySelector.
2
Read the current value with the appropriate property or method.
3
Transform the value in JavaScript (compute, concatenate, validate).
4
Write the new value back to the element using the same property or setter method.
5
Verify the change in the browser or console to confirm it rendered correctly.

Example 1: Dynamic Greeting

Given a heading with id "greeting", update it to say the user's name and add a highlight class.

HTML
<h1 id="greeting">Welcome!</h1>
JavaScript
const name = "Alice";
const el = document.getElementById("greeting");

// Step 1: Update text
el.textContent = "Welcome, " + name + "!";

// Step 2: Add a CSS class
el.classList.add("highlighted");

Example 2: Dark Mode Toggle

Toggle a "dark-mode" class on the body element, and update a button's text to reflect the current state.

JavaScript
const btn = document.querySelector("#toggle-btn");

btn.addEventListener("click", function() {
  // Toggle the class on <body>
  document.body.classList.toggle("dark-mode");

  // Read whether class is now present
  const isDark = document.body.classList.contains("dark-mode");

  // Update button text
  btn.textContent = isDark
    ? "Switch to Light"
    : "Switch to Dark";
});

Example 3: Image Swap

Change the src and alt attributes of an image based on a data attribute.

HTML
<img id="photo" src="sunset.jpg" alt="Sunset"
     data-next="mountain.jpg">
JavaScript
const photo = document.getElementById("photo");

// Read a data attribute
const nextSrc = photo.getAttribute("data-next");
// Or use: photo.dataset.next

// Update src and alt
photo.setAttribute("src", nextSrc);
photo.setAttribute("alt", "Mountain view");

Common Mistakes

✕ Using innerHTML for plain text
Setting innerHTML when only text changes wastes performance and opens XSS holes. Use textContent instead.
✕ Overwriting className
Assigning el.className = "new" erases all existing classes. Use classList.add() to append safely.
✕ Selecting before DOM loads
If your script runs in the <head>, elements don't exist yet. Place scripts at the end of <body> or use DOMContentLoaded.

Quick Reference Table

Task Read Write
Text content el.textContent el.textContent = "..."
HTML content el.innerHTML el.innerHTML = "..."
Any attribute el.getAttribute("x") el.setAttribute("x", "v")
Check class el.classList.contains("x") --
Add class -- el.classList.add("x")
Remove class -- el.classList.remove("x")
Toggle class -- el.classList.toggle("x")

Question 1 of 5

What does el.textContent return?

Question 2 of 5

Which method would you use to add the class "active" to an element without removing its existing classes?

Question 3 of 5

Given <a id="link" href="/home">Home</a>, which expression correctly reads the href value?

Question 4 of 5

What is the security risk of using innerHTML with user-supplied input?

Question 5 of 5

What does el.classList.toggle("visible") do if the element already has the class "visible"?