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.

A JavaScript data file with code brackets and a laptop.
Inside this lesson 10 sections 5 questions 9 figures

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

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.

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.

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.

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.

DOM Tree for a Simple HTML Pagedocument<html><head><body><title>"My Page"<h1 id="hdr">"Welcome!"<img>src="photo.jpg"alt="A photo"LegendElement nodeText node (child)Attributes (on the element)
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.

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

constelement=document.getElementById(′myId′);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

constelement=document.querySelector(′.highlight′);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

lettext=element.textContent;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!′;element.textContent = 'Hello, World!';

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.

DOM Read / Update Workflow1. SELECT the elementgetElementById('id')querySelector('sel')querySelectorAll('sel')2. READ or UPDATETEXT / CONTENT.textContentPlain text only, safe.innerHTMLIncludes HTML tags, use carefullyATTRIBUTES.getAttribute('name')Read any attribute value.setAttribute('n', 'v')Write / overwrite an attribute.src .href .alt .idDirect property access (shortcut)
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).
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

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

    Step 1 — Select the name element

    Use document.getElementById('userName') to grab the <h2> element. Store it in a variable for easy reuse.
    const nameEl = document.getElementById('userName');
  2. 2

    Step 2 — Read the current name

    Access 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. 3

    Step 3 — Update the name text

    Assign a new string to textContent to change what the user sees. The browser immediately re-renders the heading.
    nameEl.textContent = 'Alex Rivera';
  4. 4

    Step 4 — Update the avatar image

    Select 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. 5

    Step 5 — Update the bio using innerHTML

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

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.

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

Comparison of textContent and innerHTML

🔒

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.

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

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

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?
Show answer
The HTML source code is the original file stored on the server. When the browser loads it, it creates the DOM — a live, in-memory tree of objects representing the page. JavaScript modifies this in-memory tree, not the original file. The browser then re-renders the visible page based on the updated DOM. This is why changes made with JavaScript disappear if you refresh the page — the browser rebuilds the DOM from the original HTML file each time.

Question 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".
Show answer
First, select the element using its 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

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".
Show answer
Start by selecting the image: 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

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".
Show answer
Select both elements: 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

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?
Show answer
This is a classic Cross-Site Scripting (XSS) vulnerability. Because 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.

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