Tutorial

How To Access Elements in the DOM

Updated on June 23, 2022
How To Access Elements in the DOM

Introduction

In Understanding the DOM Tree and Nodes, we went over how the DOM is structured as a tree of objects called nodes, and that nodes can be text, comments, or elements. Usually when we access content in the DOM, it will be through an HTML element node.

In order to be confident in accessing elements in the DOM, it’s good to have a working knowledge of CSS selectors, syntax and terminology as well as an understanding of HTML elements. In this tutorial, you will learn several ways to access elements in the DOM: by ID, class, tag, and query selectors.

Overview

Here is a table overview of the five methods we will cover in this tutorial.

Gets Selector Syntax Method
ID #demo getElementById()
Class .demo getElementsByClassName()
Tag demo getElementsByTagName()
Selector (single) querySelector()
Selector (all) querySelectorAll()

It is helpful when studying the DOM to work with the examples on your own to ensure that you are understanding and retaining the information you learn.

Create a new file, access.html, in your own project to work through the examples along with this article. If you are unsure how to work with JavaScript and HTML locally, review our How To Add JavaScript to HTML tutorial.

access.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Accessing Elements in the DOM</title>

  <style>
    html { font-family: sans-serif; color: #333; }
    body { max-width: 500px; margin: 0 auto; padding: 0 15px; }
    div, article { padding: 10px; margin: 5px; border: 1px solid #dedede; }
  </style>

</head>

<body>

  <h1>Accessing Elements in the DOM</h1>

  <h2>ID (#demo)</h2>
  <div id="demo">Access me by ID</div>

  <h2>Class (.demo)</h2>
  <div class="demo">Access me by class (1)</div>
  <div class="demo">Access me by class (2)</div>

  <h2>Tag (article)</h2>
  <article>Access me by tag (1)</article>
  <article>Access me by tag (2)</article>

  <h2>Query Selector</h2>
  <div id="demo-query">Access me by query</div>

  <h2>Query Selector All</h2>
  <div class="demo-query-all">Access me by query all (1)</div>
  <div class="demo-query-all">Access me by query all (2)</div>

</body>

</html>

In this HTML file, we have many elements that we will access with different document methods. When we render the file in a browser, it will look similar to this:

Browser rendering of access.html page

We’ll be using the different methods that we outlined in the Overview above to access the available elements in the file.

Accessing Elements by ID

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.

document.getElementById();

In order to be accessed by ID, the HTML element must have an id attribute. You have a div element with an ID of demo you can use:

<div id="demo">Access me by ID</div>

In the Console, get the element and assign it to the demoId variable.

  1. const demoId = document.getElementById('demo');

Logging demoId to the console will return our entire HTML element.

  1. console.log(demoId);
Output
<div id="demo">Access me by ID</div>

You can be sure you’re accessing the correct element by changing the border property to purple.

  1. demoId.style.border = '1px solid purple';

Once you do so, your live page will look like this:

Browser rendering of ID element styling

Accessing an element by ID is an effective way to get an element quickly in the DOM. However, it has drawbacks: an ID must always be unique to the page, and therefore you will only ever be able to access a single element at a time with the getElementById() method. If you wanted to add a function to many elements throughout the page, your code would quickly become repetitious.

Accessing Elements by Class

The class attribute is used to access one or more specific elements in the DOM. You can get all the elements with a given class name with the getElementsByClassName() method.

document.getElementsByClassName();

Now we want to access more than one element, and in our example we have two elements with a demo class.

<div class="demo">Access me by class (1)</div>
<div class="demo">Access me by class (2)</div>

Access these elements in the Console and put them in a variable called demoClass.

  1. const demoClass = document.getElementsByClassName('demo');

At this point, it might be tempting to modify the elements the same way you did with the ID example. However, if you try to run the following code and change the border property of the class demo elements to orange, you will get an error.

  1. demoClass.style.border = '1px solid orange';
Output
Uncaught TypeError: Cannot set property 'border' of undefined

The reason this doesn’t work is because instead of just getting one element, you have an array-like object of elements.

  1. console.log(demoClass);
Output
(2) [div.demo, div.demo]

JavaScript arrays must be accessed with an index number. You can change the first element of this array by using an index of 0.

  1. demoClass[0].style.border = '1px solid orange';

Generally when accessing elements by class, we want to apply a change to all the elements in the document with that particular class, not just one. You can do this by creating a for loop, and looping through every item in the array.

  1. for (i = 0; i < demoClass.length; i++) {
  2. demoClass[i].style.border = '1px solid orange';
  3. }

When you run this code, your live page will be rendered like this:

Browser rendering of class element styling

You have now selected every element on the page that has a demo class, and changed the border property to orange.

Accessing Elements by Tag

A less specific way to access multiple elements on the page would be by its HTML tag name. You access an element by tag with the getElementsByTagName() method.

document.getElementsByTagName();

For our tag example, we’re using article elements.

<article>Access me by tag (1)</article>
<article>Access me by tag (2)</article>

Just like accessing an element by its class, getElementsByTagName() will return an array-like object of elements, and you can modify every tag in the document with a for loop.

  1. const demoTag = document.getElementsByTagName('article');
  2. for (i = 0; i < demoTag.length; i++) {
  3. demoTag[i].style.border = '1px solid blue';
  4. }

Upon running the code, the live page will be modified like so:

Browser rendering of tag element styling

The loop changed the border property of all article elements to blue.

Query Selectors

If you have any experience with the jQuery API, you may be familiar with jQuery’s method of accessing the DOM with CSS selectors.

$('#demo'); // returns the demo ID element in jQuery

You can do the same in plain JavaScript with the querySelector() and querySelectorAll() methods.

document.querySelector();
document.querySelectorAll();

To access a single element, you can use the querySelector() method. In our HTML file, we have a demo-query element

<div id="demo-query">Access me by query</div>

The selector for an id attribute is the hash symbol (#). You can assign the element with the demo-query id to the demoQuery variable.

  1. const demoQuery = document.querySelector('#demo-query');

In the case of a selector with multiple elements, such as a class or a tag, querySelector() will return the first element that matches the query. You can use the querySelectorAll() method to collect all the elements that match a specific query.

In the example file, you have two elements with the demo-query-all class applied to them.

<div class="demo-query-all">Access me by query all (1)</div>
<div class="demo-query-all">Access me by query all (2)</div>

The selector for a class attribute is a period or full stop (.), so you can access the class with .demo-query-all.

  1. const demoQueryAll = document.querySelectorAll('.demo-query-all');

Using the forEach() method, you can apply the color green to the border property of all matching elements.

  1. demoQueryAll.forEach(query => {
  2. query.style.border = '1px solid green';
  3. });

Browser rendering of querySelector() styling

With querySelector(), comma-separated values function as an OR operator. For example, querySelector('div, article') will match div or article, whichever appears first in the document. With querySelectorAll(), comma-separated values function as an AND operator, and querySelectorAll('div, article') will match all div and article values in the document.

Using the query selector methods is extremely powerful, as you can access any element or group of elements in the DOM the same way you would in a CSS file. For a complete list of selectors, review CSS Selectors on the Mozilla Developer Network.

Complete JavaScript Code

Below is the complete script of the work you did above. You can use it to access all the elements on our example page. Save the file as access.js and load it in to the HTML file right before the closing body tag.

access.js
// Assign all elements
const demoId = document.getElementById('demo');
const demoClass = document.getElementsByClassName('demo');
const demoTag = document.getElementsByTagName('article');
const demoQuery = document.querySelector('#demo-query');
const demoQueryAll = document.querySelectorAll('.demo-query-all');

// Change border of ID demo to purple
demoId.style.border = '1px solid purple';

// Change border of class demo to orange
for (i = 0; i < demoClass.length; i++) {
  demoClass[i].style.border = '1px solid orange';
}

// Change border of tag demo to blue
for (i = 0; i < demoTag.length; i++) {
  demoTag[i].style.border = '1px solid blue';
}

// Change border of ID demo-query to red
demoQuery.style.border = '1px solid red';

// Change border of class query-all to green
demoQueryAll.forEach(query => {
  query.style.border = '1px solid green';
});

Your final HTML file will look like this:

access.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Accessing Elements in the DOM</title>

  <style>
    html { font-family: sans-serif; color: #333; }
    body { max-width: 500px; margin: 0 auto; padding: 0 15px; }
    div, article { padding: 10px; margin: 5px; border: 1px solid #dedede; }
  </style>

</head>

<body>

  <h1>Accessing Elements in the DOM</h1>

  <h2>ID (#demo)</h2>
  <div id="demo">Access me by ID</div>

  <h2>Class (.demo)</h2>
  <div class="demo">Access me by class (1)</div>
  <div class="demo">Access me by class (2)</div>

  <h2>Tag (article)</h2>
  <article>Access me by tag (1)</article>
  <article>Access me by tag (2)</article>

  <h2>Query Selector</h2>
  <div id="demo-query">Access me by query</div>

  <h2>Query Selector All</h2>
  <div class="demo-query-all">Access me by query all (1)</div>
  <div class="demo-query-all">Access me by query all (2)</div>

  <script src="access.js"></script>

</body>

</html>

You can continue to work on these template files to make additional changes by accessing HTML elements.

Conclusion

In this tutorial, we went over 5 ways to access HTML elements in the DOM — by ID, by class, by HTML tag name, and by selector. The method you will use to get an element or group of elements will depend on browser support and how many elements you will be manipulating. You should now feel confident to access any HTML element in a document with JavaScript through the DOM.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Tutorial Series: Understanding the DOM — Document Object Model

The Document Object Model, usually referred to as the DOM, is an essential part of making websites interactive. It is an interface that allows a programming language to manipulate the content, structure, and style of a website. JavaScript is the client-side scripting language that connects to the DOM in an internet browser.

About the authors


Default avatar

Tech Writer at DigitalOcean


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
3 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks, really helped me out. Great tutorial and easy to follow

Hi Tania, I too thought it was a great tutorial – all of them are so far. Really helpful. There is one thing, though, that I think could be improved. When you are processing elements that were accessed using .getElementsByClassName, or .getElementsByTagName, you handle the returned variable with a for loop, but when you are processing elements that were accessed using .querySelectorAll you handle the returned variable with the .forEach method. I think it would have been good to have some explanation for why – which, if I understand correctly, is because the “getElementsBy…()” methods return “HTMLCollection” objects, which cannot be processed with .forEach like arrays, while the querySelectorAll() method returns “NodeList” objects, which, in modern browsers, CAN be processed with .forEach like arrays. I think a little explanation about that would have been helpful.

Great explanation Tania on how to access to DOM elements, I have understood the array idea behind these types of objects in Javascript. Thanks to you, I will be able to automate a web page data introduction via Internet Explorer and PowerShell.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel