The DOM: selecting and changing elements
Course contents (16 lessons)
- Getting started
- What is JavaScript and where does it run?
- Variables with let and const
- Values and operators
- Data types: numbers, strings, booleans, null and undefined
- Operators: arithmetic, comparison and logical
- Strings and template literals
- Making decisions and repeating work
- Conditionals: if, else and switch
- Loops: for, while and for...of
- Functions
- Functions: declarations, parameters and return values
- Arrow functions and callbacks
- Arrays and objects
- Arrays: creating, reading and changing lists
- Array methods: map, filter, find and reduce
- Objects: properties, methods and copying
- Scope and the browser
- Scope and closures, gently
- The DOM: selecting and changing elements
- Events: reacting to clicks, input and forms
- Final project
- Project: build a to-do list in the browser
What the DOM is
When a browser loads an HTML page, it turns the tags into a tree of objects in memory. This tree is the Document Object Model, or DOM. JavaScript can read this tree and change it, and the page updates on screen straight away.
The entry point is the global document object. You can try everything here in the browser console on any page. For a file of your own, use this starter page:
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello</h1>
<ul id="list">
<li class="item">One</li>
<li class="item">Two</li>
</ul>
<script src="app.js"></script>
</body>
</html>
The script is at the end of body so the elements exist when the code runs. If you put it in head, document.querySelector would find nothing, because the page is not built yet.
Selecting elements
The modern way is querySelector, which takes a CSS selector.
const title = document.querySelector("#title"); // by id
const firstItem = document.querySelector(".item"); // first with class
const allItems = document.querySelectorAll(".item"); // all matches
console.log(title.textContent); // "Hello"
console.log(allItems.length); // 2
querySelector returns one element, or null if nothing matches. querySelectorAll returns a list that you can loop with for...of or forEach. If you know CSS selectors, you already know how to select.
Changing content
title.textContent = "Welcome to my page";
textContent sets plain text. There is also innerHTML, which parses HTML:
title.innerHTML = "Welcome, <em>friend</em>";
Be careful with innerHTML. If you insert text that came from a user, they can inject a <script> or other markup and attack your visitors. That is called cross-site scripting (XSS). For anything that is not your own fixed markup, use textContent.
Changing styles and classes
You can set inline styles directly, but a better habit is to toggle CSS classes and keep the look in your stylesheet.
title.style.color = "tomato"; // inline style
title.classList.add("highlight");
title.classList.remove("highlight");
title.classList.toggle("highlight"); // add if missing, remove if present
console.log(title.classList.contains("highlight")); // true
Attributes
const link = document.querySelector("a");
link.setAttribute("href", "https://example.com");
console.log(link.getAttribute("href"));
link.removeAttribute("target");
const input = document.querySelector("input");
input.value = "Default text"; // form values are properties
input.disabled = true;
Creating and adding elements
You can build new elements from code:
const list = document.querySelector("#list");
const newItem = document.createElement("li");
newItem.textContent = "Three";
newItem.classList.add("item");
list.append(newItem); // add to the end
list.prepend(document.createElement("li")); // add to the start
newItem.remove(); // remove it again
Steps: create the element, set its text and classes, then attach it to something that is already on the page. Until you attach it, the element exists only in memory.
Here is a complete example that builds a list from an array:
const fruits = ["Mango", "Apple", "Banana"];
const ul = document.querySelector("#list");
ul.innerHTML = ""; // clear the old items
for (const fruit of fruits) {
const li = document.createElement("li");
li.textContent = fruit;
ul.append(li);
}
Notice that we used createElement and textContent, not string-building with innerHTML. It is safer and, with practice, just as quick to write.
Walking the tree
Elements know their neighbours:
const first = document.querySelector(".item");
console.log(first.parentElement.id); // "list"
console.log(first.nextElementSibling.textContent); // "Two"
console.log(document.querySelector("#list").children.length);
You rarely need this when you can select directly, but it comes in handy inside event handlers.
Common mistakes
- Script in the head without defer. Elements are not there yet, and
querySelectorreturnsnull. Put the script at the end ofbodyor adddeferto the tag. - Reading a property of null.
Cannot read properties of nullmeans your selector matched nothing. Check the spelling and the#or.prefix. - **Using
innerHTMLwith user input.** UsetextContent. - Treating querySelectorAll like one element. It gives a list. Loop over it.
- Forgetting to attach a new element.
createElementalone does not show anything.
Try it yourself
- Open the console on any web page, select the first
h1orh2and change its text. - Select every
alink on a page and print theirhrefvalues. - Write code that adds a new
liwith your name to the list in the starter page. - Use
classList.toggleto add and remove a class calleddarkon thebodyelement.
const list = document.querySelector("#list");
const newItem = document.createElement("li");
newItem.textContent = "Three";
newItem.classList.add("item");
list.append(newItem); // add to the end
list.prepend(document.createElement("li")); // add to the start
newItem.remove(); // remove it again
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account