2 Ways to Select All Elements with Same Class in JavaScript

When you are working with vanilla JavaScript, you surely need to get elements with class names to change CSS styles. This post explains how to select all the elements with the same class in JavaScript.

Method 1: Using document.getElementsByClassName to Get Elements

This is the old method to select all the elements with the given class name. In this method, you just need to pass the class name to the document.getElementsByClassName function. The following example selects all the elements with the paragraph class name in HTML.

You can read more about document.getElementsByClassName on mozzila documentation.

Method 2: Selecting Same Class Elements with document.querySelectorAll

This is a new way to select all the elements from DOM with the same class names. You have to pass the parameter with .className syntax because it’s a kind of CSS selector. The following example uses document.querySelectorAll to get all the elements with paragraph class names from the HTML DOM.

It is recommended to use the 2nd method because it is used for class names and other selectors. Please read more about querySelectorAll on mozzilla documentation.


You can select all the elements with the same class using 2 methods. The first method is to use document.getElementsByClassName and the second method is to use document.querySelector.

Latest articles

Related articles