Accessing DOM Elements Tutorial
Tags: javascript, webdev, tutorial, beginners
Published: 2022-08-01 16:18:18

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:
```html
<!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:
![The DOM](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/20ndxacs4hhswfvn8qj8.png)

## 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.
```js
document.getElementById();
```
To access an element in this way it must have an `id` attribute. Such as:
```html
<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`.
```js
const testId = document.getElementById('test');
```
We can see the result with a console log:
```js
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:
```js
testId.style.backgroundColor = 'blue';
```
_Note_: We’ll dive deeper into altering style later in the article!

Our live page will now look like this:
![DOM Elements](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/61zmwqbuxlzpjb41cxj4.png)
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()`.
```js
document.getElementsByClassName();
```
In our example, we have two elements with the _class_ of `test`.
```html
<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`.
```js
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!
```js
testClass.style.backgroundColor = 'red';

// 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.
```js
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:
```js
testClass[0].style.backgroundColor = 'red';
```
And to change all our class elements, we could use a `for` loop:
```js
for (i = 0; i < testClass.length; i++) {
  testClass[i].style.backgroundColor = 'red';
}
```
_Note_: I’ll be looking into the fundamentals of arrays and loops in future articles.

Here’s our updated example:
![DOM Elements-2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rckbv9oh1pq3l3t93cei.png)

## getElementsByTagName()
Another way to access multiple elements is via its HTML tag name using `getElementsByTagName()`.
```js
document.getElementsByTagName();
```
Here are the section elements in our example:
```html
<section>I'm a tag</section>
<section>I'm another tag</section>
```
Let's add them to a variable:
```js
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.
```js
for (i = 0; i < testTag.length; i++) {
  testTag[i].style.backgroundColor = 'green';
}
```

![DOM Elements-3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n4b47hhd2jvvrd3chwfk.png)

## Query Selectors
Let’s take a look at our final element access methods `querySelector()` and `querySelectorAll()`.
```js
document.querySelector();
document.querySelectorAll();
```
To target a single element, we use the `querySelector()` method. Let’s access the following element in our example:
```html
<div id="test-query">Use a query selector</div>
```
As it’s an `id` attribute, we use the hash `#` symbol when assigning our element:
```js
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:
```html
<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:
```js
const testQueryAll = document.querySelectorAll('.test-query-all');
```
And let’s use a `forEach()` method to modify our styles, like so:
```js
testQueryAll.forEach(query => {
  query.style.backgroundColor = 'orange';
});
```
![DOM Elements-4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ilod9qf0pkzrqhioynbo.png)
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](https://twitter.com/RembertDesigns) where I post daily about Tech related things!
![Buy Me A Coffee](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ijinng8k7bf23v0o6gkj.png) If you enjoyed this article & would like to leave a tip — click [here](https://www.buymeacoffee.com/rembertdesigns)

### 🌎 Let's Connect

- [Portfolio](https://www.rembertdesigns.co/)

- [Twitter](https://twitter.com/RembertDesigns)

- [LinkedIn](https://www.linkedin.com/in/rrembert/)

- [Hashnode](https://rembertdesigns.hashnode.dev/)

- [Devto](https://dev.to/rembertdesigns)

- [Medium](https://medium.com/@rembertdesigns)

- [Github](https://github.com/rembertdesigns)

- [Codepen](https://codepen.io/rembertdesigns)