Accessing DOM Elements Tutorial

Richard Rembert - Aug 1 '22 - - Dev Community

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>
Enter fullscreen mode Exit fullscreen mode

Our output looks like this:
The DOM

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();
Enter fullscreen mode Exit fullscreen mode

To access an element in this way it must have an id attribute. Such as:

<div id="test">I'm an ID</div>
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode

We can see the result with a console log:

console.log(testId);

// output: 

<div id="test">I'm an ID</div>
Enter fullscreen mode Exit fullscreen mode

And let’s be sure we’re accessing the right element by giving it some style:

testId.style.backgroundColor = 'blue';
Enter fullscreen mode Exit fullscreen mode

Note: We’ll dive deeper into altering style later in the article!

Our live page will now look like this:
DOM Elements
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();
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

In the Console, let's get both of these elements and add them to a variable called testClass.

const testClass = document.getElementsByClassName('test');
Enter fullscreen mode Exit fullscreen mode

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 = 'red';

// output:

Uncaught TypeError: Cannot set property 'backgroundColor' of undefined
    at <anonymous>
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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 = 'red';
Enter fullscreen mode Exit fullscreen mode

And to change all our class elements, we could use a for loop:

for (i = 0; i < testClass.length; i++) {
  testClass[i].style.backgroundColor = 'red';
}
Enter fullscreen mode Exit fullscreen mode

Note: I’ll be looking into the fundamentals of arrays and loops in future articles.

Here’s our updated example:
DOM Elements-2

getElementsByTagName()

Another way to access multiple elements is via its HTML tag name using getElementsByTagName().

document.getElementsByTagName();
Enter fullscreen mode Exit fullscreen mode

Here are the section elements in our example:

<section>I'm a tag</section>
<section>I'm another tag</section>
Enter fullscreen mode Exit fullscreen mode

Let's add them to a variable:

const testTag = document.getElementsByTagName('section');
Enter fullscreen mode Exit fullscreen mode

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 = 'green';
}
Enter fullscreen mode Exit fullscreen mode

DOM Elements-3

Query Selectors

Let’s take a look at our final element access methods querySelector() and querySelectorAll().

document.querySelector();
document.querySelectorAll();
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

As it’s an id attribute, we use the hash # symbol when assigning our element:

const testQuery = document.querySelector('#test-query');
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

As we’re now working with class attributes, we use the period . symbol to access our elements:

const testQueryAll = document.querySelectorAll('.test-query-all');
Enter fullscreen mode Exit fullscreen mode

And let’s use a forEach() method to modify our styles, like so:

testQueryAll.forEach(query => {
  query.style.backgroundColor = 'orange';
});
Enter fullscreen mode Exit fullscreen mode

DOM Elements-4
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.

Summary

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!

Conclusion

If you liked this blog post, follow me on Twitter where I post daily about Tech related things!
Buy Me A Coffee If you enjoyed this article & would like to leave a tip — click here

🌎 Let's Connect

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .