textContent and innerText
Learn to read and change an element's text.
Read and write text with textContent
To read or change an element's text, use the textContent property. It is both readable and writable.
Reading: const text = heading.textContent; gives the text inside the element.
Writing: heading.textContent = "New heading"; changes the element's text; the entire previous content is replaced.
textContent treats the value as plain text; HTML tags are not parsed. That makes it safe.
When is innerText different?
innerText also gives an element's text; but it has some differences from textContent.
innerText ignores text of elements hidden with display: none; it takes the browser's visible layout into account. textContent gives all the text, including hidden elements.
Also, innerText is slower because it performs layout calculations. In most cases textContent is preferred.
Exercise Update the status text
Select the element with id "status" using querySelector and assign it to statusEl. Then set statusEl.textContent to "Loaded".
Show example solution
Select with querySelector('#status'), then write statusEl.textContent = 'Loaded'.
Example solution:
const statusEl = document.querySelector("#status");
statusEl.textContent = "Loaded";
Test yourself
-
How do you change an element's text?
- heading.textContent()
- heading.text = "..."
- heading.setValue("...")
- heading.textContent = "..."
Show answer
heading.textContent = "..." — Correct! textContent is a property; assign with =.
-
Update the text
const status = document.querySelector("#status"); status.____ = "Ready";Show answer
const status = document.querySelector("#status"); status.textContent = "Ready"; -
Match each property to its behavior
- textContent
- all text, safe
- innerText
- visible text, layout aware
- innerHTML
- parses as HTML, risky
- document.title
- the page's title
-
Why is textContent safer?
- It treats HTML tags as text and does not parse them
- It encrypts communication with the server
- It is shorter to write
- It automatically reloads the page
Show answer
It treats HTML tags as text and does not parse them — Correct! textContent treats HTML as text; tags are not parsed.