JavaScriptintermediate 9 min
Select elements on a page and change their text, style and structure with JavaScript.
How to find elements with querySelector, change their text, classes and styles, and create and remove elements.
The DOM is how JavaScript talks to a web page. Every interactive site, from a like button to a full app, works by reading and changing the DOM.
When a browser loads HTML it builds the DOM (Document Object Model): a tree of objects, one per element. JavaScript gets at it through the global document object.
Finding elements:
document.querySelector("#id") returns the first element matching a CSS selector.document.querySelectorAll(".item") returns all matches.Changing them:
el.textContent = "Hello" sets plain text. (Prefer it to innerHTML, which can run unsafe HTML.)el.classList.add("on"), .remove("on"), .toggle("on").el.style.color = "tomato" sets an inline style.el.setAttribute("href", "...") sets an attribute.Creating and removing:
document.createElement("li") makes a new element.parent.append(child) adds it.el.remove() deletes it.querySelector("#title") finds the heading. We change its text and colour.<li>, set its text and append it to the list.Add a fourth name, and make every item bold by setting li.style.fontWeight = "bold".
querySelector returns null, and then null.textContent throws an error.innerHTML with user input, which can allow script injection.querySelectorAll returns a list, not one element.document is the entry point.querySelector, change with textContent, classList and style.createElement, add with append, delete with remove.Next: reacting to what users do.
<h2 id="title">Hello</h2>
<ul id="list"></ul>
<script>
const title = document.querySelector("#title");
title.textContent = "Changed by JavaScript";
title.style.color = "tomato";
const list = document.querySelector("#list");
for (const name of ["Asha", "Ravi", "Zoya"]) {
const li = document.createElement("li");
li.textContent = name;
list.append(li);
}
list.firstElementChild.classList.add("first");
list.lastElementChild.remove();
</script>