Learn How to Use DOM Selectors
The Document Object Model (DOM) is the structural representation of an HTML document. The DOM is a tree of nodes that the browser creates for each webpage on the internet.
The DOM is object-oriented. Each element in the DOM has its own set of attributes and methods that you can access using JavaScript.
In this tutorial article, you’ll learn how to use DOM selector functions to access elements of a webpage.
How to Access DOM Elements
You can access the top-level DOM element of a webpage via the global document object. For example, if you have a web page like the following:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<section id="home">
<h1>Welcome</h1>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur asperiores voluptatum et repellat?
Quae iusto non eligendi hic accusamus itaque ut in delectus sint perspiciatis quos rem a, atque veniam.
</p>
</section>
<section id="about">
<h2>About</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur asperiores voluptatum et repellat?
Quae iusto non eligendi hic accusamus itaque ut in delectus sint perspiciatis quos rem a, atque veniam.
</p>
</section>
<section id="blog">
<h2>Articles</h2>
<div class="articles" id="article-1">
<h3>Article Title One</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur asperiores voluptatum et repellat?
Quae iusto non eligendi hic accusamus itaque ut in delectus sint perspiciatis quos rem a, atque veniam.
</p>
<a href="#"> Read More </a>
</div>
<div class="articles" id="article-2">
<h3>Article Title Two</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur asperiores voluptatum et repellat?
Quae iusto non eligendi hic accusamus itaque ut in delectus sint perspiciatis quos rem a, atque veniam.
</p>
<a href="#"> Read More </a>
</div>
<div class="articles" id="article-3">
<h3>Article Title Three</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur asperiores voluptatum et repellat?
Quae iusto non eligendi hic accusamus itaque ut in delectus sint perspiciatis quos rem a, atque veniam.
</p>
<a href="#"> Read More </a>
</div>
<div class="articles" id="article-4">
<h3>Article Title Four</h3>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur asperiores voluptatum et repellat?
Quae iusto non eligendi hic accusamus itaque ut in delectus sint perspiciatis quos rem a, atque veniam.
</p>
<a href="#"> Read More </a>
</div>
</section>
</body>
</html>
Typing document in your browser console and hitting enter will produce the following output:
The output in your console is interactive. You can click on the head and body elements to expand them. Doing so will produce the following output:
Each section element in the <body> tag is also expandable. Depending on the structure of a web page, the elements will keep expanding to reveal more elements. This should give you a clearer understanding of the DOM’s structure.
The document object has a special property, body, representing the body element. So, to access the body element you can type the following in the console:
document.body
This will produce the following output:
But this is as far as you can go using object properties. Every page has a head and a body but is otherwise unique. So typing document.body.section or anything similar will simply not work as you might like. Instead, there are methods that you can call on the document object to access specific elements.
What Are DOM Element Selectors?
DOM element selectors are a group of JavaScript methods that you can use on the document object to access elements in a web page. DOM element selectors have two categories—single and multiple selectors.
These functions act in a similar way to CSS selectors. They allow you to retrieve elements based on their tag name, or their id and class attributes. You can even fetch elements using any CSS selector.
The single element selectors are:
- getElementById()
- querySelector()
The multiple element selectors are:
- getElementsByTagName()
- getElementsByClassName()
- querySelectorAll()
The DOM element selector you use will depend on the element(s) that you’re trying to gain access to.
Using Single DOM Element Selectors
You’ll mostly see selectors within JavaScript applications. So, let’s move away from the console. Create a JavaScript file and link it to your HTML file using the following script tag:
<script src="main.js"></script>
Where the src value is the name of your JavaScript file. Place this script tag just before your closing body tag, </body>.
The getElementById() method provides access to a single element on a webpage using the value of its ID. In the HTML document above there are several elements with IDs. To target the div element with the “article-3” ID you can add the following code to your JavaScript file:
value = document.getElementById('article-3')
Now the div element with the article-3 ID and all its corresponding properties are accessible from the value variable. You can print the value variable to the console using the following line of code:
console.log(value)
You’ll see the class name that’s assigned to the div element as well as other important attributes, such as the inner HTML.
The other single element selector is the querySelector(). This function is more versatile, as you can pass it any CSS selector string. However, you can still only use it to select one element at a time.
For example, there’s a single class in the HTML layout above—articles. Four div elements use this class, but the querySelector() function will only return the first element that has the “articles” class.
Using querySelector() With a Class
Add the following code at the end of your script:
value = document.querySelector('.articles')
console.log(value)
This will only return the first div element with an “articles” class. Notice that you specify the selector in the same format as a CSS selector. In CSS, a leading period specifies a class name.
Using querySelector() With an ID
value = document.querySelector('#article-3')
console.log(value)
This code will return the only element with an “article-3” ID, the third div element with an “articles” class. Again, the selector string uses standard CSS syntax, with a # symbol specifying an ID.
Using Multiple DOM Element Selectors
The remaining selector functions retrieve groups of elements. They are getElementsByTagName(), getElementsByClassName(), and querySelectorAll().
Using getElementsByTagName()
The getElementsByTagName() selector fetches a group of elements with the same tag name. For example, if you want to select all the h2 elements on a web page, you can use the following code:
value = document.getElementsByTagName('h2')
console.log(value)
This stores all the h2 elements in an HTML collection called value.
Using getElementsByClassName()
The getElementsByClassName() selector returns a collection of elements with the same class name.
value = document.getElementsByClassName('articles')
console.log(value)
Inserting the code above into your JavaScript file will return the four div elements with the “articles” class name in the browser console.
Using querySelectorAll()
The querySelectorAll() method returns a node list of all elements that match the given selector. To access all paragraph elements in the blog section, you can use the following code:
value = document.querySelectorAll('#blog p')
console.log(value)
You can even include several selectors in the string, separating each with a comma, just as in CSS:
value = document.querySelectorAll('h2, .articles')
console.log(value)
Use DOM Selectors to Make Dynamic Web Pages
At this point, you should have a clear understanding of the DOM and how it works. You should also know the different single and multiple selectors, as well as how to use them.
Still, gaining access to HTML elements is only the first step in what you can do with DOM selectors. DOM selectors will go a long way in helping you develop the functional aspects of your website, such as handling onclick and onscroll events.