← Web basics: HTML, CSS and JavaScript
Finding elements and changing text
document.querySelector, querySelectorAll and textContent.
When the browser reads your HTML, it builds a tree of objects called the DOM (Document Object Model). JavaScript can reach into that tree through document. document.querySelector(selector) returns the first element matching a CSS selector, the same selectors you used in CSS, like "#total" or ".price". document.querySelectorAll(selector) returns all matches as a list you can loop over. Every element has a textContent property: read it to get its text, or set it to replace the text.
<h1 id="title">Weather</h1>
<p class="temp">21</p>
<p class="temp">24</p>
<script>
const title = document.querySelector("#title");
title.textContent = "Weather today";
const temps = document.querySelectorAll(".temp");
for (const t of temps) {
t.textContent = t.textContent + " °C";
}
</script>The first part finds the heading by id and replaces its text. The second finds both .temp paragraphs and adds " °C" to each one's current text.
If nothing matches, querySelector returns null, and using it gives an error like "Cannot set properties of null". Check the selector spelling, the # or . and that the script runs after the HTML.
There is also innerHTML, which reads and writes HTML tags as well as text. Prefer textContent when you only need text, especially text a visitor typed: it can never accidentally create tags.