JavaScript AcademyProfessional Engineering
Level 3 · Interactive Web ApplicationsModule 11: The Document Object ModelLesson 53 of 150About 40 minutes

Lesson 53: Reading and changing content

01Opening question

A cart badge shows "3". After a click it should show "4". How does JavaScript change what the page says, and how do you avoid showing a visitor's input as code?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

Assigning to textContent replaces an element's text, and the preview updates at once.

const title = document.querySelector("#title");
title.textContent = "Welcome back, Ada";
console.log(title.textContent);

03Objective and prerequisites

Learning objective: Read and change element text with textContent, read input values, understand when innerHTML is appropriate, and avoid injecting untrusted HTML.

You need: Lesson 52: Selecting elements

Skills practised: The DOM, Changing content.

04Explanation

el.textContent reads all the text inside an element. Assigning to it replaces the content with plain text.

Form fields store what the user typed in .value, which is always a string, even for numbers.

el.innerHTML reads or writes the HTML markup inside an element. Writing it makes the browser parse tags.

Never put untrusted text (anything a user typed or a server returned) into innerHTML. Use textContent, which shows it as plain text.

05Definitions

textContent
The text inside an element; assigning it replaces the content with plain text.
innerHTML
The HTML markup inside an element; assigning it parses the string as HTML.
value
The current text of a form field, always a string.
XSS
Cross-site scripting: running attacker-supplied code by inserting untrusted HTML into a page.

Open the full glossary

06Visual learning object

DOM update visualizer. Run updates on a live preview and compare what textContent and innerHTML do with the same string.

Loading the interactive object…

Open the full DOM update visualizer page with its guided experiment.

07Examples

ex-053-01Change text Browser page (sandboxed preview)

textContent reads and replaces an element's text.

const title = document.querySelector("#title");
const count = document.querySelector("#count");
title.textContent = "Your cart";
count.textContent = `${3} items`;
console.log(title.textContent, "|", count.textContent);
Sample input
None
Expected output
Your cart | 3 items

The heading reads Your cart and the paragraph reads 3 items.

Common mistake
Assigning to el.text or el.value on a heading, which does nothing visible.
Try this
Make the count say 1 item (singular) when the number is 1.
Source
examples/ex-053-01-text.js

ex-053-02textContent versus innerHTML Browser page (sandboxed preview)

The same string becomes text or markup.

const name = "<b>Ada</b>";
document.querySelector("#a").textContent = name;
document.querySelector("#b").innerHTML = name;
console.log(document.querySelector("#a").textContent);
console.log(document.querySelector("#b").textContent);
console.log(document.querySelector("#b").children.length);
Sample input
None
Expected output
<b>Ada</b> Ada 1
Common mistake
Using innerHTML for a name a visitor typed.
Try this
Try the name <img src=x alt="x"> in both and compare.
Source
examples/ex-053-02-safe-vs-html.js

ex-053-03Read an input Browser page (sandboxed preview)

value is always a string; convert before calculating.

const qty = document.querySelector("#qty");
console.log(qty.value, typeof qty.value);
console.log(qty.value + 2);
console.log(Number(qty.value) + 2);
Sample input
None
Expected output
3 string 32 5
Common mistake
Adding to value directly and getting string concatenation.
Try this
Set qty.value = "10" from code and log it.
Source
examples/ex-053-03-input-value.js

ex-053-04textContent versus innerText Browser page (sandboxed preview)

innerText only includes text that is rendered.

const msg = document.querySelector("#msg");
console.log(msg.textContent);
console.log(msg.innerText);
Sample input
None
Expected output
Saved (draft) Saved
Common mistake
Expecting textContent to hide text that CSS hides.
Try this
Remove the hidden class from the CSS and compare again.
Source
examples/ex-053-04-visible-text.js

ex-053-05Write a summary from data Browser page (sandboxed preview)

Build the text in JavaScript, then write it once.

const cart = [{ name: "Tea", qty: 2 }, { name: "Cake", qty: 1 }];
const items = cart.reduce((n, line) => n + line.qty, 0);
const text = `${items} items: ${cart.map((l) => l.name).join(", ")}`;
document.querySelector("#summary").textContent = text;
console.log(document.querySelector("#summary").textContent);
Sample input
None
Expected output
3 items: Tea, Cake
Common mistake
Writing to the page inside a loop many times instead of once.
Try this
Add a third product and run again.
Source
examples/ex-053-05-summary.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Show the greeting

Use textContent to change a paragraph.

const greeting = document.querySelector("#greeting");
greeting.value = "Hello, Ada";
console.log(greeting.textContent);

Order total

Read inputs, convert them and write a result.

const price = document.querySelector("#price");
const qty = document.querySelector("#qty");
const total = document.querySelector("#total");
// TODO: show "Total: $13.50" in #total

Safe scoreboard

Write untrusted text safely.

// Write renderScore(el, name, score)

09Prediction

Commit to an answer first, then run the real code to compare.

// HTML: <input id="n" value="7">
const n = document.querySelector("#n").value;
console.log(n + 1, n * 2);

What is printed?

10Debugging investigation

The calculator shows 23 instead of 5

Adding 2 and 3 in the quick calculator shows 23.

const a = document.querySelector("#a");
const b = document.querySelector("#b");
const sum = document.querySelector("#sum");
sum.textContent = "Sum: " + (a.value + b.value);
console.log(sum.textContent);

More cases in the Debugging Detective Laboratory

11Practical scenario

Showing user-generated content

A comments widget shows names and messages typed by visitors. Every value is written with textContent, so a message containing HTML tags or script attributes appears as harmless text instead of running in other visitors' browsers.

// li.textContent = `${comment.author}: ${comment.message}`;
console.log("Untrusted text goes into textContent");

12Knowledge check

1. Which property safely writes text a visitor typed?

  • innerHTML
  • textContent
  • outerHTML
  • insertAdjacentHTML

2. With <input id="q" value="2">, what is printed?

console.log(document.querySelector("#q").value + 2);
  • 22
  • 4
  • "2"2
  • NaN

3. What is printed?

const p = document.createElement("p");
p.innerHTML = "<i>x</i>";
console.log(p.children.length);
  • 1
  • 0
  • <i>x</i>
  • An error

4. Why does the page still show the old total?

document.querySelector("p#total").value = "Total: 10";
  • A paragraph has no value; use textContent
  • The total is wrong
  • innerHTML is required
  • Numbers cannot be shown

5. What happens to elements inside a div when you assign div.textContent = "Hi"?

  • They stay and Hi is added
  • They are removed and replaced by the text
  • Only text nodes change
  • Nothing happens

6. A server returns a product name. How should it be displayed?

  • el.innerHTML = name
  • el.textContent = name
  • document.write(name)
  • eval(name)

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Show the greeting: The page shows the greeting; Prints it
  • Order total: #total shows the total; Uses the inputs
  • Safe scoreboard: Prints both scores; No HTML was created; Two list items

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-03-interactive-web-applications/module-11-the-document-object-model/lesson-053-reading-and-changing-content/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • textContent reads and writes plain text.
  • Input value is always a string: convert it.
  • innerHTML parses markup; never use it with untrusted text.
  • innerText reflects only visible text.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation changing page content safely
Context: I am learning changing page content safely in JavaScript.
Task: Explain textContent, innerHTML and input value, including why innerHTML with user input is dangerous.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction changing page content safely drill
Context: I have practised changing page content safely.
Task: Give me six snippets that read and write content and ask what each prints or shows.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging changing page content safely bug
Context: My page shows 32 instead of 5 when I add two input values.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation changing page content safely practice
Context: I finished the changing page content safely exercises.
Task: Create three exercises that read inputs and update text safely.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review changing page content safely review
Context: Here is my code that uses changing page content safely.
Task: Review my DOM output code for XSS risks and missing type conversion.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.