Javascript Get Element By Class
Want to use Javascript to get an element by its class? There are a couple of ways you can do that:
- getElementsByClassName()
- querySelectorAll()
But there are a few things you might want to consider before you implement either of these methods.
Let’s take a closer look.
Using Javascript to Get an Element by Class
The first way to use Javascript to get an element by class is to the getElementsByClassName method.
This method is used to get a group of elements by a particular class name. All elements, regardless of type, will be returned in an array-like object which can be accessed in a variety of ways.
Elements can then be accessed how you would normally access arrays in javascript – directly or dynamically, depending on your requirements.
Why a Group of Elements and Not Just One?
The getElementsByClassName Javascript method returns a group of elements in an array object rather than just one because classes are designed to be used multiple times on any given webpage and are used as such.
If you know there will always be one identifier for one element, then it would be better to use the ID attribute to access the element with the getElementById Javascript method. Or you could also use custom Data Attributes and use the querySelector Javascript method to access the element.
But what if you’re dealing with dynamic data? What if you don’t know how many elements there are? What if there could be one element or many elements and you need to anticipate that?
In this scenario, the getElementsByClassName Javascript method is absolutely an acceptable way to do so.
So let’s take a look at it in action.
Using get Elements By Class Name Javascript method to get an element by class
This is the scenario: we have 4 divs with the same class and we want to collect them together to be able to access them.
Here’s what the divs look like:
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
Here’s how we collect them using getElementsByClassName:
const items = document.getElementsByClassName('item');
If we were to console log the items variable, we’d get the following output:
HTMLCollection(4) [div.item, div.item, div.item, div.item]
0: div.item
1: div.item
2: div.item
3: div.item
length: 4
__proto__: HTMLCollection
As you can see, this function has collected all of our elements with the item class together and output them into an array. Now, we can access the collections like we would an array:
We have access to the the length property, so we can count how many elements on the page have the item class:
items.length;
//Output is 4
Like any array, we can access any of the items directly:
Items[0]
//Output is: <div class="item">Item 1</div>
Or we can loop through the array:
for(let i = 0; i < items.length; i++) {
console.log(items[i]);
}
//Output is:<div class="item">Item 1</div> <div class="item">Item 2</div> <div class="item">Item 3</div> <div class="item">Item 4</div>
Multiple Class Names
But there’s a little more cool functionality to the getElementsByClassName that you might not be aware of: the method accepts multiple class names.
So imagine that you have a set of elements with the same class, but you wanted to filter elements out by a second class.
Take these elements for example:
<div class="item dogs">Item 1</div>
<div class="item cats">Item 2</div>
<div class="item fish">Item 3</div>
<div class="item fish">Item 4</div>
It’s pretty much the same as before, but each element has a second class – an animal class. Let’s say we wanted to select all the elements that have the item class that also have the fish class.
We’d do this:
const filterItems = document.getElementsByClassName('item fish');
//Output: <div class="item fish">Item 3</div> <div class="item fish">Item 4</div>
Now let’s say we altered our elements to add a class for the animals that are still currently on sale or have been sold:
<div class="item dogs sale">Item 1</div>
<div class="item cats sale">Item 2</div>
<div class="item fish sale">Item 3</div>
<div class="item fish sold">Item 4</div>
And we want to see all the fish that are for sale:
const saleItems = document.getElementsByClassName('item fish sale');
//Output: <div class="item fish sale">Item 3</div>
That’s pretty useful, right?
You can check out the Codepen I used for this demonstration here; fork it and have a play around!
Now, let’s take a look at the querySelectorAll Javascript method and see how we can use this to achieve the same results.
Using querySelectorAll
Another way you can use Javascript to get an element by a class is to use the querySelectorAll Javascript method.
The difference between the getElementsByClassName and querySelectorAll Javascript methods isn’t that much when it comes to getting elements by a class name.
Overall, however, the querySelectorAll method is more powerful and allows you to grab pretty much any element by pretty much any means imaginable.
What I mean by that is you can use this method to select an element by class, id, element type, data attribute or a combination of those elements.
Let’s take a look at the the querySelectorAll Javascript method in action.
First, let’s define our elements:
<div class="items">
<div id="1" data-type="fish" data-status="sale" class="item">Fish 1 for Sale</div>
<div id="2" data-type="doggo" data-status="sale" class="item">Doggo 1 for Sale</div>
<div id="3" data-type="doggo" data-status="sold" class="item">Doggo 2 sold</div>
<div id="4" data-type="fish" data-status="sale" class="item">Fish 2 for Sale</div>
</div>
You’ll notice this time I’ve been a little creative with my elements, adding both IDs and data attributes to them.
Now, let’s take a look at some of our queries in action. First, we’re going to use querySelectorAll to get all the elements with the item class.
let items = document.querySelectorAll('.item');
//Output
NodeList(4):
div#1.item:
div#2.item:
div#3.item:
div#4.item
length: 4__proto__: NodeList
This will return all 4 divs with the item class.
Interestingly, we’d get pretty much the same result with any of the following querySelectorAll queries:
let items = document.querySelectorAll('[data-type=”fish]');
let items = document.querySelectorAll('div.item');
let items = document.querySelectorAll('[data-status]');
let items = document.querySelectorAll('#1, #2, #3, #4, #5');
There are a couple of things to note in the examples above.
The div.Item
The first is that we had to use div.item there. If we used just div, the parent element would’ve been included too, as it’s also a div.
Accessing Data Attributes
The second is the way in which you call data attributes with querySelectorAll. Data attributes are to be wrapped in square brackets and can be called just based on the data attribute itself or the data attribute and its value.
As you can see from the example above, I’ve used both methods. The first is to get all of the elements that have a data-type of “fish” and the second is to get me all elements with the status data attribute.
I go into a little more detail about access Data Attributes in my Javascript Get Data Attribute article – it’s well worth a read if you’re interested.
Accessing IDs
IDs have to be accessed by naming them all like in the example above. There is no way to just select every element that has an ID and other methods, such as data attributes or classes are a better way of getting access to a collection of elements in this manner.
Javascript Get Element By Class: Conclusion
If you want to access a group of elements in Javascript by class, then using the getElementsByClassName or querySelectorAll methods are your two best options. Both return the same results, BUT the getElementsByClassName method
However, if your goal is to get just one element then the getElementsByClassName is probably not your best option. Getting the element by its ID or data attribute is, depending what attributes the element holds.