How to Get Element by Class Name in Javascript

Last Updated on April 24, 2024 by Roshan Parihar

To get an element by class name in JavaScript, use the document.getElementsByClassName() method that returns an array-like object of all the elements with the same class name.

There can be more than one element with the same class name on a web page. So, it requires to use Elements in getElementsByClassName and not the Element because there can be multiple elements with the same class.

Let’s see different useful examples to learn the method.

How to Get Element by Class Using Javascript

If you want to get the element by class in javascript, you have to use getElementsByClassName() method. It requires to pass the element class name as its argument.

Example 1

Output

This is a simple paragraph.


You can get the element with its index value that starts from zero (0). That means, to get the first element with the class name, pass the index value zero (0). For the second element with a matching class name, pass index value one (1). The below example gets the second element with the same class name.

Example 2

The above example applies the CSS color to the element using JavaScript. This applies only to the single matching specified element.

Using For Loop to Find All Elements

If you want to get all the elements by class name, you have to use getElementsByClassName() with for loop in javascript. The main use of the for loop is to get all the elements using the index value in a variable.

It first calculates the length of elements with the matching class name. After that, it performs the loop until it reaches the length of the number of times the element is present on a page.

Example 3

Output

First paragraph.

Second paragraph.

Third paragraph.

Forth paragraph.

Fifth paragraph.


The above example applies the CSS to the alternate matching elements.

Get Element and Change text Content Using Javascript

Get the element by class name and change the content, you have to use innerHTML with getElementsByClassName() function of javascript. See the example to learn the method.

Example 4

Output

This is my paragraph



The above example contains the button element. When you click the button given above, it changes the inner content of the selected element by class name.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.