In this tutorial, we’re going to take a look at several methods we can use to access DOM elements, such as: getElementById()getElementsByClassName()getElementsByTagName()querySelector() and querySelectorAll().

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:

DOM Example

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:

DOM Example Selection

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:

DOM Example Updated Selection

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';
}

DOM Example Updated Selection

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';
});

DOM Example Query Selector All

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: