DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

How to use JavaScript to get elements by class name?

In this short tutorial, we use JavaScript to get element by class name. We break down the concept, explain the code and then discuss the limitations of the method used.

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.

Table of Contents - Javascript get element by class:

How does the class attribute work?

The class attribute is an optional property of an HTML element. This attribute can be used on any HTML element. Once a class is created their name can be used by CSS or JavaScript to apply a particular style or to perform certain tasks. This ensures that all the elements belonging to a particular class behave and appear in a similar fashion.
The below code is an example of a class attribute.

<h2 class="classname">Title</h2>
Enter fullscreen mode Exit fullscreen mode

Using the JavaScript getElementByClassName() method:

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.

The syntax is as follows:

var elements = document.getElementsByClassName(name);
Enter fullscreen mode Exit fullscreen mode

Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.

Code and Explanation:

Let’s take a sample HTML code:

<header>
<nav>
        <ul id="freelancer">
            <li class="item">Name</li>
            <li class="item">Skills</li>
            <li class="item price">Cost</li>
            <li class="item">Projects</li>
        </ul>
</nav>
</header>
Enter fullscreen mode Exit fullscreen mode

Now since we intend to look for the element in a particular section we first identify the section along with the ID.

let docs = document.getElementByID('#freelancer');
let elements = freelancer.getElementsByClassName('item');
Enter fullscreen mode Exit fullscreen mode

Now ‘elements’ contain the list of elements with the class name ‘item’.

Limitation & Caveats - JavaScript get element by class:

When using the aforementioned method, note that
If you are trying to get elements with the different class names their names must be separated by whitespace and not a comma.
Class selectors cannot be used in this method.

Oldest comments (0)