JavaScript: Get elements by class name.

This is a JavaScript tutorial on how to get HTML elements by their class name. In this guide, I will show you how to loop through these elements. In addition, I will also show you how to retrieve only one of the elements in question.

How to get HTML elements by their class name.

To retrieve a list of every HTML element that has a particular CSS class name, we can use the document.getElementsByClassName() method like so:

In the code above, you can see that we have an unordered list. Inside our unordered list, we have two list elements that have the CSS class “inactive”. As a result, we must use the document.getElementsByClassName() method in order to retrieve them.

If you run the code above and check your browser’s console, you will see that the method has returned an array-like structure called a HTMLCollection object. This HTMLCollection object contains the two UL list items that have the CSS class “inactive”.

Looping through HTML elements that have a CSS class name.

The HTMLCollection is an array-like object that has a length property. As a result, we can loop through it like a regular array.

To loop through the HTMLCollection object, we can use a for loop like so:

In the code above, we looped through the <li> elements in our HTMLCollection object. Inside our loop, we retrieved each element by using the NodeList.item() method. We then printed out the text inside those list items by accessing the Element.innerHTML property.

Note that this “for loop” will work in every major browser, including older browsers such as Internet Explorer.

Getting only one element by class name.

If you are looking to only get one element that has a particular class name, then you do something like this:

Here, we were able to get the first element in our HTMLCollection object by providing the NodeList.item() method with 0 as the index parameter.

What if there are no elements with that class name?

If there are no HTML elements with the class name in question, then the document.getElementsByClassName() method will return an empty HTMLCollection object. Consequently, if you use NodeList.item() on an empty HTMLCollection object, the method will return a NULL value.

Check to see if an element with a specific CSS class exists.

To check if there are any HTML elements that contain a certain CSS class, we can do something like this:

Note: If you reference the HTMLCollection object like a regular array instead of using the item() method, it will result in an undefined value.

Facebook Comments