Lesson 11: The DOM: Selecting, Changing and Creating Elements
The DOM, the Document Object Model, is the browser's live map of a web page. When the browser reads your HTML, it builds a tree of objects, one for each element, and JavaScript can reach into that tree, read it, change it and add to it. That is how a page updates without reloading: a script finds the heading, changes its text, and the browser redraws the page instantly. The DOM is the bridge between your JavaScript and your HTML, and almost everything interactive on the web, from a like button to a live search box, is built by selecting elements, changing them, and listening for events, which is the next lesson. This lesson covers the selecting and changing half of that bridge.
Selecting elements
You select elements with methods on the document object, and the most useful is document.querySelector(), which takes a CSS selector and returns the first matching element: document.querySelector('#score') finds the element with the id score, and document.querySelector('.card') finds the first element with the class card. Its partner, document.querySelectorAll(), returns all matching elements, which you can then loop through, as in document.querySelectorAll('li').forEach(function (item) { ... });. Older methods such as getElementById() and getElementsByClassName() still work, but querySelector covers both jobs with one familiar syntax, since you already know CSS selectors. Always check that a selection found something before using it: if the selector is wrong, querySelector returns null, and trying to use null gives an error, so a quick if (element) guard saves a lot of confusion.
Reading and changing content
Once you have an element, you can read and change its text with textContent, which is the safe choice for plain text, because it treats everything as text and never runs it as code. The property innerHTML lets you set HTML inside an element, which is powerful but risky: if the HTML comes from a visitor, a malicious visitor could inject a script, an attack called cross-site scripting, which you will study properly in the cybersecurity course. The rule is simple: use textContent for text, and use innerHTML only with HTML you wrote yourself. You can also change attributes, such as element.src for an image, and change styles through element.style, though for anything bigger than one small change it is better to add or remove a class with element.classList.add('hidden') and let your CSS describe what that class means, which keeps style in the stylesheet where it belongs.
const heading = document.querySelector('h1');
const button = document.querySelector('#greet');
const list = document.querySelector('#todo');
button.addEventListener('click', function () {
heading.textContent = 'Hello, visitor!';
const item = document.createElement('li');
item.textContent = 'Say hello';
list.appendChild(item);
});
Creating and removing elements
You can build new elements from JavaScript with document.createElement(), which makes an element that exists in memory but is not yet on the page, until you attach it with a method such as appendChild(), which adds it as the last child of a parent. The example above creates a list item, sets its text, and appends it to a list when a button is clicked, which is the core pattern behind every comment box, shopping list and search result on the web. You can also remove an element with element.remove(), replace one with element.replaceWith(), and insert before a chosen sibling with parent.insertBefore(). Because these changes happen in the live DOM, the browser redraws immediately, and because they happen in memory first, you can build a whole piece of content and attach it in one step, which is faster and cleaner than adding it piece by piece.
Thinking in the tree
It helps to picture the DOM as a family tree: the document is the root, the html element is its child, head and body are the html element's children, and every element has a parent, children and siblings. JavaScript can walk that tree, for example with element.parentElement or element.children, though in practice you will usually select what you need directly with querySelector and change it, rather than climbing the tree by hand. The important mental shift is to stop thinking of a web page as a fixed document and start thinking of it as data your script can read and rewrite. That shift is what makes everything in the rest of this course possible, and it is also why a solid understanding of HTML structure matters: JavaScript can only work with the page you built, so clean, semantic HTML makes the scripting easier, just as it made the styling easier.
Key Terms
- DOM
- Document Object Model, the browser's live tree of objects representing a web page.
- querySelector()
- A method that returns the first element matching a CSS selector.
- querySelectorAll()
- A method that returns all elements matching a CSS selector.
- textContent
- A property that reads or sets an element's plain text, safely, without running HTML.
- innerHTML
- A property that reads or sets the HTML inside an element; powerful but risky with visitor input.
- classList
- An object for adding, removing and toggling classes on an element, such as classList.add('hidden').
- createElement()
- A method that builds a new element in memory, ready to be attached to the page.
Discussion Questions
- Why is textContent safer than innerHTML when the text comes from a visitor?
- If querySelector returns null, what probably went wrong, and how would you check?
- Why is it better to change an element's class than to set its style directly from JavaScript?
Practice Questions
- What does document.querySelector('#score') return?
- When should you use textContent, and when innerHTML?
- What does document.createElement('li') do, and what must happen before the item appears on the page?
- What does element.classList.add('hidden') do?
- What is the difference between querySelector and querySelectorAll?
Show answers
- The first element with the id score. The # means an ID selector, and querySelector returns the first match, or null if there is none.
- Use textContent for plain text and innerHTML only with HTML you wrote yourself. textContent never runs code, while innerHTML with visitor input can let an attacker inject a script.
- It builds a new li element in memory. It only appears on the page once you attach it, for example with list.appendChild(item).
- It adds the class hidden to the element. Your CSS then decides what hidden means, such as display: none, keeping style in the stylesheet.
- querySelector returns the first match; querySelectorAll returns all matches. The second gives a list you can loop through to change many elements at once.