Finding and Changing Elements
How to use querySelector, getElementById, and textContent to manipulate the page.
The Essentials
- The
documentAPI: Your gateway to the page. You can access properties likedocument.titleordocument.body. - Finding Single Elements: Use
document.getElementById('id')ordocument.querySelector('.class')to retrieve a specific element. - Finding Multiple Elements: Use
document.querySelectorAll()ordocument.getElementsByClassName()to get collections of elements. You can check how many were found using.length. - Changing the DOM: The
=operator lets you replace content. You can change text viaelement.textContent = "New Text", or add to it usingelement.append(" and more").
In the last post, I wrote about how JavaScript parses an HTML file into a mental model called the Document Object Model (DOM). But just knowing the DOM is there is not very useful. The real power of JavaScript comes from reading that model and changing it.
If you open the console on any webpage, the document object gives you immediate access to the structure. For example, typing document.title will return the title of the current page. Typing document.body.children will give you a collection of all the top-level elements inside the body tag.
But usually, I do not want the entire body. I want a specific thing.
Finding Specific Elements
There are a few ways to pull exact elements out of the DOM tree. Which one I use depends entirely on how the HTML is structured.
If the element has an id attribute, I am in luck. IDs are meant to be unique to a single element on the page, so I can grab it directly:
document.getElementById("board")Note the capitalization. JavaScript is very picky about camelCase, and typing a lowercase d at the end of that method is a mistake I make constantly.
What if the element does not have an ID? Maybe I want to find an element by its HTML tag, like an <h1>, or by a CSS class. For this, there is another set of methods:
// Finds all elements with the 'player' class
document.getElementsByClassName("player")
// Finds all <h1> elements
document.getElementsByTagName("h1")These methods return collections: either an HTMLCollection or a NodeList. While there are technical differences between the two, functionally they both act as groups of elements. If I want to know exactly how many elements were found, I can check the .length property on the collection.
If you are already comfortable with CSS, there is an even more powerful way to select elements. The querySelector and querySelectorAll methods let you pass in any valid CSS selector string:
// Gets the first element with the ID 'board'
document.querySelector("#board")
// Gets all elements with the class 'square'
document.querySelectorAll(".square")Changing the Page
Once I have hold of an element, I can bend it to my will.
If you type document.title = "My Page" into the console, the actual title of the tab you are looking at will change immediately. You are now the arbiter of what happens in the browser.
The same logic applies to elements inside the page. If I select an element, I can modify its text using the .textContent property.
// Replace the text entirely
document.getElementById("p1-name").textContent = "James"
// Add to the existing text
document.getElementById("p1-name").append(" and Peter")The equals sign is incredibly powerful here. It tells the browser to throw away whatever text was inside that element and replace it with exactly what you provided. If you just want to add something to the end without destroying the old content, .append() is the safer choice.
This is the foundation of web interactivity. Every complex web application you use is built on these same mechanics: find an element in the DOM, listen for a user action, and then change the DOM in response.
Further Reading and Watching
- MDN: Locating DOM elements using selectors - The official guide on query selectors.
Video:
- FrontendMasters: JavaScript First Steps - The source course for this foundational concept.
Keep reading