Index

The Document Object Model (DOM)

JavaScript for Beginners

11.1 Understanding the DOM Tree

The Document Object Model (DOM) is the way browsers represent a web page internally. It acts as a tree-like structure that models every part of an HTML document, allowing JavaScript to access, modify, and interact with the page dynamically.

The DOM as a Tree Structure

Imagine your HTML document as a big family tree. At the top is the root, and branches grow down into smaller branches and leaves. Similarly, the DOM tree starts from the document root node and branches out into elements like <html>, <body>, <div>, and more.

Each node in this tree represents a part of the document:

How the Browser Builds the DOM

When a browser loads an HTML page, it reads the HTML code from top to bottom and creates the DOM tree node by node:

<html>
  <body>
    <h1>Welcome</h1>
    <p>Hello, world!</p>
  </body>
</html>

This HTML creates a DOM tree like this:

document
 └─ html
     └─ body
         ├─ h1
         │    └─ "Welcome" (text node)
         └─ p
              └─ "Hello, world!" (text node)

Why the Tree Model Matters

This hierarchical tree structure lets JavaScript navigate and manipulate any part of the page easily. For example, you can find the <p> element inside <body>, change its text, add new elements, or remove existing ones—all by moving through this tree.

Think of the DOM as the living blueprint of your web page—a dynamic representation that your scripts can explore and update in real time.

Understanding the DOM tree is the first step toward mastering how web pages work behind the scenes and interact with your JavaScript code!

Index

11.2 Querying Elements (getElementById, querySelector)

To interact with a webpage’s content, JavaScript needs to select or query elements from the DOM tree. Two of the most common ways to find elements are using getElementById and querySelector.

getElementById

Example:

<div id="main-header">Welcome!</div>
const header = document.getElementById('main-header');
console.log(header.textContent); // Output: Welcome!

querySelector and querySelectorAll

Examples:

<ul>
  <li class="item">Apple</li>
  <li class="item">Banana</li>
  <li class="item">Cherry</li>
</ul>
const firstItem = document.querySelector('.item');
console.log(firstItem.textContent); // Output: Apple

const allItems = document.querySelectorAll('.item');
allItems.forEach(item => console.log(item.textContent));
// Output:
// Apple
// Banana
// Cherry

Differences and When to Use Each

Feature getElementById querySelector / querySelectorAll
Selects by Unique id Any CSS selector
Returns Single element or null Single element (querySelector) or NodeList (querySelectorAll)
Use case Fast, simple ID selection Flexible, complex selections (classes, tags, attributes, combinations)
Performance Faster for ID-based queries Slightly slower but usually negligible

Exercises

  1. Select the element with id "footer" and change its background color:
const footer = document.getElementById('footer');
footer.style.backgroundColor = 'lightblue';
  1. Select the first button with class "btn" and disable it:
const firstBtn = document.querySelector('.btn');
firstBtn.disabled = true;
  1. Select all paragraphs inside a container with id "content" and log their text:
const paragraphs = document.querySelectorAll('#content p');
paragraphs.forEach(p => console.log(p.textContent));

Summary

Mastering element querying sets the foundation for dynamic web page interactions!

Index

11.3 Modifying DOM Elements

Once you've selected elements from the DOM, the next step is to modify them to change how your webpage looks or behaves. You can update an element’s content, attributes, styles, or classes—all in real time using JavaScript.

Changing Text Content

To update the visible text inside an element, use:

Example:

<p id="message">Hello, world!</p>
const message = document.getElementById('message');

// Change text content (safe, no HTML interpreted)
message.textContent = 'Welcome to JavaScript!';

// Or update HTML content (can include tags)
message.innerHTML = 'Welcome to <strong>JavaScript</strong>!';

Modifying Styles

You can change CSS styles directly via the .style property.

Example:

message.style.color = 'blue';
message.style.fontWeight = 'bold';
message.style.backgroundColor = '#f0f0f0';

This immediately updates the paragraph's color, weight, and background.

Adding, Removing, and Toggling Classes

Classes control CSS styling and can be easily manipulated with the classList property:

Example:

message.classList.add('highlight');
message.classList.remove('highlight');
message.classList.toggle('highlight'); // Adds if missing, removes if present

Modifying Attributes

Attributes like src (images), href (links), alt, or title can be changed with:

Example:

<a id="myLink" href="https://example.com">Visit Example</a>
<img id="myImage" src="image1.jpg" alt="Image">
const link = document.getElementById('myLink');
const image = document.getElementById('myImage');

link.setAttribute('href', 'https://openai.com');
link.textContent = 'Visit OpenAI';

image.src = 'image2.jpg';
image.alt = 'New Image';

Real-Time Changes

All these modifications instantly update the page without needing to reload it. This dynamic behavior is what makes web apps interactive and responsive to user input.

Summary

Mastering DOM modifications lets you bring your web pages to life with JavaScript!

Index

11.4 Creating and Removing DOM Elements

Manipulating the DOM isn't limited to modifying existing elements — you can also create new elements dynamically and remove elements when they are no longer needed. This ability is essential for building interactive, dynamic web pages.

Creating New Elements with document.createElement

To create a new element, use the document.createElement method:

const newDiv = document.createElement('div');
newDiv.textContent = 'Hello, I am a new div!';

At this point, newDiv exists only in memory — it’s not yet visible on the page.

Adding Elements to the DOM

To insert your new element into the document, you attach it to an existing element using methods like:

Example: Add a new item to a list

<ul id="todoList">
  <li>Buy groceries</li>
  <li>Walk the dog</li>
</ul>
const list = document.getElementById('todoList');
const newItem = document.createElement('li');
newItem.textContent = 'Read a book';

// Add new item to the end of the list
list.appendChild(newItem);

Inserting Before a Specific Element

const secondItem = list.children[1]; // The second <li>
const urgentItem = document.createElement('li');
urgentItem.textContent = 'Pay bills';

// Insert urgentItem before secondItem
list.insertBefore(urgentItem, secondItem);

Removing Elements from the DOM

There are two common ways to remove elements:

  1. Using the parent element’s removeChild() method:
const firstItem = list.children[0];
list.removeChild(firstItem);
  1. Using the element’s own remove() method (modern browsers):
const lastItem = list.lastElementChild;
lastItem.remove();

Practical Scenario: Dynamic Content Management

Imagine a simple to-do app where users can add and remove tasks dynamically.

// Add task
function addTask(text) {
  const li = document.createElement('li');
  li.textContent = text;
  list.appendChild(li);
}

// Remove first task
function removeFirstTask() {
  if (list.firstElementChild) {
    list.firstElementChild.remove();
  }
}

addTask('Learn DOM manipulation');
removeFirstTask();

Summary

By mastering creation and removal, you control the structure and content of your web pages dynamically!

Index