In this tutorial, weâre going to take a look at several methods we can use to access DOM elements. Weâll be working with an HTML file that consists of a variety of elements, this way we can practice each method.
The HTML is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Master the DOM!</title>
</head>
<body>
<h1>Master the DOM!</h1>
<div id="test">I'm an ID</div>
<div class="test">I'm a class</div>
<div class="test">I'm another class</div>
<section>I'm a tag</section>
<section>I'm another tag</section>
<div id="test-query">Use a query selector</div>
<div class="test-query-all">Use query selector ALL</div>
<div class="test-query-all">Use query selector ALL</div>
</body>
</html>
Our output looks like this:
getElementById()
Perhaps the most simple way to access a single element in the DOM is by its unique id
. To do this we use the getElementById()
 method.
document.getElementById();
To access an element in this way it must have an id
 attribute. Such as:
<div id="test">I'm an ID</div>
With our HTML file open in the browser, open up the Console tab of Developer Tools. And letâs get that element and assign it to a variable named testId
.
const testId = document.getElementById('test');
We can see the result with a console log:
console.log(testId);
// output:
<div id="test">I'm an ID</div>
And letâs be sure weâre accessing the right element by giving it some style:
testId.style.backgroundColor = 'red';
Note:Â Weâll dive deeper into altering style later in the article!
Our live page will now look like this:
Accessing an element via its id
 is simple enough, however, it can only connect you to a single element at a time (as id
âs must be unique). So let's look at some more methods.
getElementsByClassName()
When we want to get one or more elements in the DOM, we can access elements by class name using getElementsByClassName()
.
document.getElementsByClassName();
In our example, we have two elements with the class of test
.
<div class="test">I'm a class</div>
<div class="test">I'm another class</div>
In the Console, let's get both of these elements and add them to a variable called testClass
.
const testClass = document.getElementsByClassName(âtestâ);
However, if we attempt to modify our elements in the same way we did with the previous ID example, weâd run into an error!
testClass.style.backgroundColor = 'green';
// output:
Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
at <anonymous>
This wonât work as instead of accessing one element, weâre accessing multiple elements that are stored in an array-like object.
console.log(testClass);
// Output:
HTMLCollection(2) [div.test, div.test]
When working with arrays, we access elements using an index number, the numbers start from 0
. So we can change our first class element like so:
testClass[0].style.backgroundColor = 'green';
And to change all our class elements, we could use a for
 loop:
for (i = 0; i < testClass.length; i++) {
testClass[i].style.backgroundColor = 'green';
}
Note:Â Iâll be looking into the fundamentals of arrays and loops in future articles.
Hereâs our updated example:
getElementsByTagName()
Another way to access multiple elements is via its HTML tag name using getElementsByTagName()
.
document.getElementsByTagName();
Here are the section
 elements in our example:
<section>I'm a tag</section>
<section>I'm another tag</section>
Let's add them to a variable:
const testTag = document.getElementsByTagName(âsectionâ);
Again, weâre working with an array-like object of elements, so let's modify all our section
 tags with a for
 loop.
for (i = 0; i < testTag.length; i++) {
testTag[i].style.backgroundColor = 'blue';
}
Query Selectors
Letâs take a look at our final element access methods querySelector()
 and querySelectorAll()
.
document.querySelector();
document.querySelectorAll();
To target a single element, we use the querySelector()
 method. Letâs access the following element in our example:
<div id="test-query">Use a query selector</div>
As itâs an id
 attribute, we use the hash #
 symbol when assigning our element:
const testQuery = document.querySelector(â#test-queryâ);
If there were multiple instances of the element selected with querySelector()
, only the first would be returned. To collect all elements matching a query, weâd use querySelectorAll()
.
Our example contains two elements with the test-query-all
 class:
<div class="test-query-all">Use query selector ALL</div>
<div class="test-query-all">Use query selector ALL</div>
As weâre now working with class
 attributes, we use the period .
 symbol to access our elements:
const testQueryAll = document.querySelectorAll(â.test-query-allâ);
And letâs use a forEach()
 method to modify our styles, like so:
testQueryAll.forEach(query => {
query.style.backgroundColor = 'yellow';
});
Additionally, query selector methods have the ability to work with multiple element types. For example:
querySelector('section, article')
 would match with whichever tag appears first, and:
querySelectorAll('section, article')
 would match with all section
 and article
 tags within the document.
Query selector methods are very powerful! You can use them to access any element or group of elements in the DOM, in the same way as you would when selecting elements in CSS.
Wrapping up
And that's all for today! Weâve learned all about the DOM, and worked with the DOM tree and nodes to learn all about accessing and working with DOM elements.
In the next tutorial, weâll move on to traversing and modifying elements. Stay tuned!
Related Posts:
A little about me..
Hey, Iâm Tim! đ
Iâm a freelance business owner, web developer & author. I teach both new and experienced freelancers how to build a sustainable and successful freelancing business. Check out my Complete Guide to Freelancing if you'd like to find out more.
While you're here, you can browse through my blogs where I post freelancing tips, code tutorials, design inspiration, useful tools & resources, and much more! You can also join the newsletter, or find me on X.
Thanks for reading! đ