JAVASCRIPT

JavaScript DOM: Syntax, Usage, and Examples

The DOM is the browser’s object-based representation of an HTML page, and JavaScript uses it to read, change, and build page content. Once you know how to work with the DOM, you can turn a static page into something interactive.


How to Use the DOM

You don’t “write DOM code” in one special syntax like a loop or a function. Instead, you use JavaScript methods and properties to find elements, listen for events, and update the page.

Basic syntax you’ll see all the time

// Find an element
const heading =document.querySelector("h1");

// Read or change text
heading.textContent ="Hello from JavaScript";

// Change styles
heading.style.color ="purple";

That’s the core workflow:

  1. Select something from the page
  2. Read or change it
  3. Repeat when users interact with it

Selecting elements

Most DOM work starts by selecting elements. You’ll typically use these:

const button =document.querySelector("button");
const items =document.querySelectorAll(".item");

  • querySelector() returns the first match
  • querySelectorAll() returns a NodeList of all matches

Changing content and attributes

Once you have an element, you can update it:

const message =document.querySelector("#message");

message.textContent ="Saved!";
message.classList.add("success");
message.setAttribute("aria-live","polite");

Handling events

Events are what make pages feel “alive.” A button click, typing in a field, scrolling, and even hovering are events.

const likeButton =document.querySelector("#like-btn");
const count =document.querySelector("#count");

let likes =0;

likeButton.addEventListener("click",() => {
  likes +=1;
  count.textContent = likes;
});

Now your page reacts when someone clicks, instead of just sitting there like a poster on a wall.


When to Use the DOM

The DOM matters any time your site needs to respond to a user, update content, or connect HTML with logic.

1) Updating page content based on user actions

Buttons, forms, and menus all depend on DOM updates.

Examples:

  • Showing a “Thanks!” message after form submission
  • Expanding or collapsing an FAQ section
  • Displaying a cart count when someone adds an item

2) Validating forms and showing feedback

Front-end validation often happens through DOM changes like adding error messages or highlighting fields.

3) Building UI from data

If you load data from an API, you usually take that data and generate DOM elements like cards, table rows, or list items.

4) Creating small interactions without a full framework

A lot of useful UI behavior can happen with plain JavaScript:

  • Dark mode toggle
  • Tabs
  • Dropdown menus
  • Popups

Examples of the DOM

Example 1: Toggle dark mode

This is a classic starter feature that teaches selection, events, and class switching.

<buttonid="theme-toggle">Toggle theme</button>

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

toggle.addEventListener("click",() => {
document.body.classList.toggle("dark");
});

Add CSS like:

.dark {
background:#111;
color:#eee;
}

Now the page flips themes with one click.


Example 2: Show a validation message under an input

You can check input value and show feedback immediately.

<label>
  Email:
<inputid="email"type="email" />
</label>
<pid="error"></p>

const emailInput =document.querySelector("#email");
const error =document.querySelector("#error");

emailInput.addEventListener("input",() => {
if (!emailInput.value.includes("@")) {
    error.textContent ="Please enter a valid email address.";
  }else {
    error.textContent ="";
  }
});

This makes your form feel responsive, like it’s helping the user instead of waiting for them to mess up.


Example 3: Generate a list from an array

You’ll do this constantly when showing data.

<ulid="tasks"></ul>

const tasks = ["Buy oat milk","Reply to Alex","Water the plants"];
const list =document.querySelector("#tasks");

tasks.forEach(task => {
const li =document.createElement("li");
  li.textContent = task;
  list.appendChild(li);
});

This creates list items dynamically instead of hardcoding them in HTML.


Example 4: Remove an element when a button is clicked

Useful for dismissible alerts, deleting items, or clearing notifications.

<divclass="alert">
<span>Profile updated successfully.</span>
<buttonclass="close">X</button>
</div>

const closeBtn =document.querySelector(".close");

closeBtn.addEventListener("click",() => {
const alertBox =document.querySelector(".alert");
  alertBox.remove();
});

The alert disappears instantly, no refresh needed.


Learn More About the DOM

DOM vs HTML

HTML is the text you write.

The DOM is what the browser builds from that text. Once the page loads, JavaScript interacts with the DOM, not the raw HTML file.

That’s why you can create new elements, remove old ones, and change the page even after the browser finishes loading.

Node vs element

A “node” is any item in the DOM tree.

That includes:

  • elements (<div>, <button>)
  • text
  • comments

An element is specifically an HTML tag node, like a <p> or <img>.

Most of the time, you’ll work with elements, but the word “node” shows up in method names like childNodes.

Common properties and methods worth memorizing

These come up constantly:

  • textContent for text updates
  • innerHTML for HTML updates (use carefully)
  • classList.add() / classList.remove() / classList.toggle()
  • setAttribute() and getAttribute()
  • createElement() and appendChild()
  • remove()

Quick example of multiple at once:

const card =document.createElement("div");
card.classList.add("card");
card.textContent ="New item added!";
document.body.appendChild(card);

Avoiding innerHTML pitfalls

innerHTML is tempting because it’s fast and easy:

container.innerHTML ="<p>Hello</p>";

But it can introduce security risks if you inject user content without escaping it. If the string contains malicious code, you could end up with an XSS issue.

For user-generated content, prefer:

const p =document.createElement("p");
p.textContent = userInput;
container.appendChild(p);

DOMContentLoaded, and why your script sometimes “does nothing”

If your JavaScript runs before the browser finishes loading the DOM, selectors might return null.

One easy fix is placing your script at the bottom of the HTML file, just before </body>.

Another option is running code after the DOM loads:

document.addEventListener("DOMContentLoaded",() => {
const button =document.querySelector("button");
  button.addEventListener("click",() =>console.log("Clicked"));
});

DOM work in modern apps

Frameworks like React, Vue, and Angular still rely on the DOM. They just manage it for you.

When you learn direct DOM manipulation first, frameworks make more sense later because you already understand what they’re doing behind the scenes.


Summary

The DOM is the browser’s live representation of your page, and JavaScript uses it to select elements, listen for events, and update content. Once you get comfortable with DOM methods like querySelector(), addEventListener(), and createElement(), you can build interactive features like form validation, toggles, dynamic lists, and responsive UI updates without reloading the page.