JavaScript Intermediate: Data, the DOM and Events
The DOM: Changing a Page with JavaScript
In this lesson you will
- Explain what the DOM is
- Select elements with querySelector
- Change text, classes and create new elements
Introduction
HTML is just text in a file. When the browser loads it, it builds a live model of the page in memory, made of objects. That model is the DOM (Document Object Model). JavaScript can read and change it, and the page updates instantly.
The simple explanation
The DOM is a tree of objects that represents your page. JavaScript can find a branch and change it.
In the examples below, the code runs inside a small web page, so you can see the result.
Finding elements
document.querySelector takes a CSS selector and returns the first matching element. querySelectorAll returns all matches.
Everything you learned about CSS selectors works here.
Quick quiz
Which method returns every element matching a selector?
Changing content
textContentsets plain text. It is the safe choice.innerHTMLsets HTML. Never put untrusted text (such as something a visitor typed) intoinnerHTML, because it can run harmful code.
Classes and attributes
classList adds, removes and toggles classes, which is much better than writing styles in JavaScript.
Creating elements
Build new elements with createElement, then add them to the page.
Quick quiz
Which is the safe way to insert text typed by a visitor into the page?
Try it yourself
Create a list from an array of your three favourite foods. Then add the class done to the second item, and style .done with a line through the text.
Summary
- The DOM is the live, object-based model of your page.
- Select with
querySelectorandquerySelectorAll. - Use
textContent(safe) andclassListto change elements. createElementandappendbuild new content.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading