JavaScript - DOM Basics

Overview

Estimated time: 20–30 minutes

The Document Object Model (DOM) represents the structure of HTML documents as a tree of nodes. JavaScript can read and modify the DOM to create dynamic web pages.

Learning Objectives

  • Understand the DOM tree structure.
  • Access and modify DOM elements using JavaScript.

Prerequisites

DOM Tree

<html>
  <body>
    <h1>Hello</h1>
  </body>
</html>

Accessing Elements

const h1 = document.querySelector('h1');
h1.textContent = 'Hi!';

Modifying the DOM

const p = document.createElement('p');
p.textContent = 'New paragraph';
document.body.appendChild(p);

Common Pitfalls

  • Modifying the DOM before it is loaded can cause errors (use DOMContentLoaded event).

Summary

The DOM is the foundation of dynamic web pages. Mastering DOM manipulation is key to interactive JavaScript apps.