COMPUTER PROGRAMMING 1 (JAVASCRIPT) • WEB BASICS (DOM & EVENTS)

Reading & Updating DOM — I can read and update element text/content and basic attributes at my level.

Learn how JavaScript reads and changes what users see on a web page in real time.

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
Brendan Eich creates JavaScript at Netscape in just 10 days, giving browsers a scripting language that can interact with HTML elements for the first time.
1998
DOM Level 1 Standard
The W3C publishes the first official DOM specification, providing a standard way for all browsers to expose HTML elements to JavaScript as objects.
2004
Gmail & AJAX Revolution
Google launches Gmail, showcasing how DOM manipulation can create app-like experiences. Pages update dynamically without full reloads, popularizing the approach.
2010s
Modern Frameworks Emerge
React, Angular, and Vue automate DOM updates at scale, but they all build on the same fundamental DOM reading and writing techniques you will learn here.

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.

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.

1

The DOM Is a Tree

The browser converts your HTML into a tree of nodes. Each tag becomes an element node, and each piece of text becomes a text node. JavaScript navigates this tree to find elements.
2

Selecting Before Acting

You must first select an element (using methods like getElementById or querySelector) before you can read or change it.
3

Reading Properties

Once selected, an element's properties — such as textContent, innerHTML, or getAttribute() — let you inspect what the element currently holds.
4

Writing / Updating

Assigning a new value to a property (e.g., el.textContent = 'Hello') or calling setAttribute() instantly updates the page. The browser re-renders only the changed portion.
✦ KEY TAKEAWAY
Think of the DOM like a filing cabinet. Each drawer (element) has a label on the outside (attributes like 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.

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.

Each colored rectangle represents an element node. Dashed lines lead to text nodes — the actual words the user sees. The <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.

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
const element = document.getElementById('myId');
'myId' must match the id attribute in your HTML exactly (case-sensitive). Returns null if no match is found.
SELECT BY CSS SELECTOR
const element = document.querySelector('.highlight');
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
let text = element.textContent;
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
element.textContent = 'Hello, World!';
Replaces all existing text inside the element. Any previous child nodes are removed.

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.

This flowchart shows the full workflow: first select an element, then either read or update its text content (left branch) or its attributes (right branch). Notice the difference between textContent (safe, plain text) and innerHTML (parses HTML, use with care).
Summary of key DOM properties and methods for reading and writing
Property / MethodReadsWritesIncludes 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

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 elementUse document.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 nameAccess nameEl.textContent to 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 textAssign a new string to textContent to change what the user sees. The browser immediately re-renders the heading.
nameEl.textContent = 'Alex Rivera';
4
Step 4 — Update the avatar imageSelect the image element and change its src attribute to load a new photo. Also update the alt attribute for accessibility.
const img = document.getElementById('avatar'); img.src = 'alex.jpg'; img.alt = 'Photo of Alex Rivera';
5
Step 5 — Update the bio using innerHTMLThis time, use innerHTML because 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.

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.

Comparison of textContent and innerHTML
FeaturetextContentinnerHTML
What it returnsPlain text only, no HTML tagsFull HTML markup as a string
When writingTreats everything as literal textParses and renders HTML tags
PerformanceFaster — no HTML parsing neededSlower — browser must parse HTML
SecuritySafe — cannot inject HTML/scriptsRisk of XSS if using user input
Best forUpdating labels, headings, plain textBuilding small HTML structures
🔒 KEY TAKEAWAY
Default to 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.

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.

From fundamentals to advanced DOM techniques
What You Learn NowWhat Comes Next
getElementById / querySelectorTraversing with parentNode, children, nextSibling
textContent / innerHTMLCreating and appending elements with createElement and appendChild
setAttribute for single attributesManipulating classList to toggle CSS classes dynamically
Manual DOM updatesVirtual DOM and reactive state in React / Vue

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain in your own words the difference between the DOM and the HTML source code. Why can JavaScript change what the user sees without changing the original HTML file?
PROBLEM 2 — BASIC CALCULATION
Given this HTML: <p id="score">Points: 42</p>, write JavaScript to select this element and change its text to "Points: 50".
PROBLEM 3 — INTERMEDIATE
You have an image element: <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".
PROBLEM 4 — APPLIED
You are building a simple quiz app. The HTML has <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".
PROBLEM 5 — CRITICAL THINKING
A developer writes: 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?

Lesson 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.

Varsity Tutors • Computer Programming 1 (JavaScript) • Reading & Updating DOM