SECTION 1
Historical Context & Motivation
In the earliest days of the web, pages were completely static. A server sent an HTML file, the browser rendered it, and that was it — nothing on the page could change unless the user clicked a link and loaded an entirely new page. If you wanted to update even a single word, the whole page had to reload from scratch. This made websites feel sluggish and limited compared to desktop applications.
The breakthrough came when browsers introduced the Document Object Model (DOM), a programming interface that lets JavaScript "reach into" a web page and read or change its content. Suddenly, developers could update text, swap images, change colors, and modify links — all without reloading the page. This single innovation transformed the web from a collection of static documents into the dynamic, interactive platform you use every day.
1995 • JavaScript Is Born
1998 • DOM Level 1 Standard
2004 • Gmail & AJAX Revolution
2010s • Modern Frameworks Emerge
The core question this lesson answers is straightforward: once the browser has loaded an HTML page, how can your JavaScript code read what is already on the page and change it on the fly? By the end, you will be able to grab any element, read its text or attributes, and update them with confidence.
SECTION 2
Core Principles & Definitions
Before you start coding, you need to understand four foundational ideas that underpin every DOM interaction. Think of these as the vocabulary and mental model you will rely on throughout this lesson and beyond.
The DOM Is a Tree
Selecting Before Acting
getElementById or querySelector) before you can read or change it.Reading Properties
textContent, innerHTML, or getAttribute() — let you inspect what the element currently holds.Writing / Updating
el.textContent = 'Hello') or calling setAttribute() instantly updates the page. The browser re-renders only the changed portion.KEY TAKEAWAY
id, class, src) and papers inside (text content). JavaScript lets you open any drawer, read the papers, swap them out, or change the label — and the user sees the change instantly.SECTION 3
Visual Explanation — The DOM Tree
The diagram below shows how a simple HTML snippet is represented as a DOM tree. Notice how every tag becomes a node, and text inside tags becomes a child text node. JavaScript's selection methods traverse this tree to locate the exact node you want.
<h1> node (pink glow) has an id attribute, and the <img> node (orange) stores its src and alt as attributes.When you use document.getElementById('hdr'), JavaScript walks this tree and returns the <h1> element node. From there, you can read its textContent (which is "Welcome!") or change it to something new. The browser instantly re-draws only the part of the page that changed — the rest stays untouched.
SECTION 4
How It Works — Selection, Reading & Writing
Step 1 — Select the Element
JavaScript provides several methods to grab elements from the DOM. The two most common at this level are document.getElementById() and document.querySelector(). The first finds an element by its unique id attribute. The second accepts any CSS selector (like ".myClass" or "p") and returns the first matching element. Both return a reference to an element object that you can store in a variable.
SELECT BY ID
'myId' must match the id attribute in your HTML exactly (case-sensitive). Returns null if no match is found.
SELECT BY CSS SELECTOR
Uses any valid CSS selector. A dot . targets a class, a hash # targets an id, and a bare tag name targets that element type.
Step 2 — Read Content or Attributes
Once you have a reference to an element, you can read its text using textContent (plain text only) or innerHTML (includes HTML tags). To read an attribute like src or href, use getAttribute('attributeName'), or access it directly as a property (e.g., element.src).
READ TEXT
Returns all text inside the element and its children as a plain string, stripping out any HTML tags.
Step 3 — Write / Update Content or Attributes
Writing is just as simple as reading — assign a new value to the same property. Setting element.textContent = 'New text' replaces the element's visible text. To update attributes, use setAttribute('name', 'value') or assign directly: element.src = 'newImage.png'. The browser re-renders automatically.
WRITE TEXT
Replaces all existing text inside the element. Any previous child nodes are removed.
SECTION 5
Key Properties & Methods in Detail
The diagram below summarizes the most important properties and methods for reading and updating DOM elements at this level. Study the flow from selection to reading to updating, and note the differences between the text-related properties.
textContent (safe, plain text) and innerHTML (parses HTML, use with care).| Property / Method | Reads | Writes | Includes HTML? |
|---|---|---|---|
textContent | ✓ | ✓ | No — plain text only |
innerHTML | ✓ | ✓ | Yes — renders tags |
getAttribute('name') | ✓ | ✗ | N/A |
setAttribute('n','v') | ✗ | ✓ | N/A |
.src, .href, .alt | ✓ | ✓ | N/A — attribute shortcuts |
Summary of key DOM properties and methods for reading and writing
SECTION 6
Worked Example — Building a Profile Card Updater
Imagine you have a simple profile card on a web page. The HTML looks like this:
Starting HTML
<div id="profile">
<h2 id="userName">Jane Doe</h2>
<img id="avatar" src="default.png" alt="User avatar">
<p id="bio">No bio yet.</p>
</div>Updating the Profile Card with JavaScript
- 1
Step 1 — Select the name element
Usedocument.getElementById('userName')to grab the<h2>element. Store it in a variable for easy reuse.const nameEl = document.getElementById('userName'); - 2
Step 2 — Read the current name
AccessnameEl.textContentto see what the element currently displays. Right now it returns"Jane Doe". You can log this to the console for verification.console.log(nameEl.textContent); // "Jane Doe" - 3
Step 3 — Update the name text
Assign a new string totextContentto change what the user sees. The browser immediately re-renders the heading.nameEl.textContent = 'Alex Rivera'; - 4
Step 4 — Update the avatar image
Select the image element and change itssrcattribute to load a new photo. Also update thealtattribute for accessibility.const img = document.getElementById('avatar'); img.src = 'alex.jpg'; img.alt = 'Photo of Alex Rivera'; - 5
Step 5 — Update the bio using innerHTML
This time, useinnerHTMLbecause you want to include a bold tag inside the paragraph. This parses the string as HTML.const bio = document.getElementById('bio'); bio.innerHTML = 'Hi! I am <strong>Alex</strong>, a web developer.';
After all five steps execute, the profile card on the page now shows "Alex Rivera" as the heading, displays a new avatar image, and has a bio with the name bolded. All of this happened without reloading the page — that is the power of DOM manipulation.
SECTION 7
textContent vs. innerHTML — Strengths & Limitations
One of the most common points of confusion for beginners is when to use textContent versus innerHTML. They look similar but behave very differently under the hood. The table below highlights their key differences so you can choose the right tool for the job.
| Feature | textContent | innerHTML |
|---|---|---|
| What it returns | Plain text only, no HTML tags | Full HTML markup as a string |
| When writing | Treats everything as literal text | Parses and renders HTML tags |
| Performance | Faster — no HTML parsing needed | Slower — browser must parse HTML |
| Security | Safe — cannot inject HTML/scripts | Risk of XSS if using user input |
| Best for | Updating labels, headings, plain text | Building small HTML structures |
Comparison of textContent and innerHTML
KEY TAKEAWAY
textContent whenever you are working with plain text. Think of innerHTML like a power tool — it is more capable, but it can be dangerous if you feed it untrusted user input. A malicious user could inject a <script> tag through innerHTML, but textContent would simply display the tag as harmless text.SECTION 8
Connection to Advanced DOM Techniques
The read-and-update skills you are learning now form the foundation for every advanced front-end technique. Whether you move on to event-driven programming, DOM traversal, or modern frameworks like React, you will always be performing some version of "select → read → update." The table below previews how today's fundamentals connect to what comes next.
| What You Learn Now | What Comes Next |
|---|---|
getElementById / querySelector | Traversing with parentNode, children, nextSibling |
textContent / innerHTML | Creating and appending elements with createElement and appendChild |
setAttribute for single attributes | Manipulating classList to toggle CSS classes dynamically |
| Manual DOM updates | Virtual DOM and reactive state in React / Vue |
From fundamentals to advanced DOM techniques
Modern frameworks automate many repetitive DOM operations, but they do not replace the need to understand what is happening underneath. When something goes wrong — and it will — knowing how to inspect and manually update the DOM gives you a debugging superpower. Master these basics, and frameworks will feel intuitive rather than magical.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
Show answer
Question 2: BASIC CALCULATION
<p id="score">Points: 42</p>, write JavaScript to select this element and change its text to "Points: 50".Show answer
id: const scoreEl = document.getElementById('score'); Then update its text content: scoreEl.textContent = 'Points: 50'; We use textContent because we are only changing plain text — there are no HTML tags involved. The browser immediately displays the new text.Question 3: INTERMEDIATE
<img id="logo" src="old-logo.png" alt="Company logo">. Write JavaScript that (a) reads and logs the current src value, (b) changes it to "new-logo.svg", and (c) updates the alt attribute to "Updated company logo".Show answer
const logo = document.getElementById('logo'); (a) Read and log the current source: console.log(logo.src); — this will output the full URL of old-logo.png. (b) Update the source: logo.src = 'new-logo.svg'; — the browser immediately loads the new image. (c) Update the alt text: logo.alt = 'Updated company logo'; or equivalently logo.setAttribute('alt', 'Updated company logo');. Both approaches work; the direct property access is more concise.Question 4: APPLIED
<h3 id="question">Loading...</h3> and <a id="hint" href="#">Need a hint?</a>. Write JavaScript that: (1) sets the question text to "What is 7 × 8?", (2) updates the link's href to "hints.html#q1", and (3) changes the link text to "Click for a hint".Show answer
const questionEl = document.getElementById('question'); and const hintLink = document.getElementById('hint'); (1) Update the question: questionEl.textContent = 'What is 7 × 8?'; (2) Change the href: hintLink.href = 'hints.html#q1'; (3) Change the link text: hintLink.textContent = 'Click for a hint'; This demonstrates updating both text content and attributes in a realistic scenario. Note that we used the direct .href property shortcut rather than setAttribute for convenience.Question 5: CRITICAL THINKING
document.getElementById('greeting').innerHTML = userInput; where userInput comes from a text field the user typed into. Explain why this could be a security risk and suggest a safer alternative. What would happen if the user typed <img src=x onerror=alert('Hacked!')> into the text field?Show answer
innerHTML parses its value as HTML, the browser would create a real <img> element. Since src=x is not a valid image, the onerror event fires and executes alert('Hacked!'). In a real attack, this could steal cookies or redirect users. The fix is simple: use textContent instead. Writing document.getElementById('greeting').textContent = userInput; treats the input as literal text, so the malicious tags are displayed as harmless characters rather than rendered as HTML.SUMMARY
Lesson Summary
Summary
The Document Object Model (DOM) is a live, in-memory tree that the browser builds from your HTML. JavaScript interacts with this tree by first selecting elements using methods like getElementById() and querySelector(), then reading their current values and updating them as needed.
For text and content, use textContent for safe plain-text operations and innerHTML when you need to insert HTML (but never with untrusted user input). For attributes like src, href, and alt, use getAttribute() and setAttribute() or access them directly as element properties. These fundamentals are the building blocks for all interactive web development — from simple page tweaks to full-scale modern applications.