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.
1 2 3 4 5 6 7 |
const allParagraphs = document.getElementsByClassName("paragraph"); console.log(allParagraphs) // output : HTMLCollection {0: HTMLParagraphElement {<p class="paragraph"></p>}, 1: H...} |
1 2 3 4 5 6 7 8 9 10 11 |
<body> <h1 id="header"></h1> <p class="paragraph">First paragraph</p> <p class="paragraph">Second paragraph</p> <p class="paragraph">Third paragraph</p> <p class="paragraph">Fourth paragraph</p> </body> |
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.
1 2 3 4 5 6 7 |
const allParagraphs = document.querySelectorAll(".paragraph"); console.log(allParagraphs) // output : HTMLCollection {0: HTMLParagraphElement {<p class="paragraph"></p>}, 1: H...} |
1 2 3 4 5 6 7 8 9 10 11 12 |
<body> <h1 id="header"></h1> <p class="paragraph">First paragraph</p> <p class="paragraph">Second paragraph</p> <p class="paragraph">Third paragraph</p> <p class="paragraph">Fourth paragraph</p> <script src="src/script.js"></script> </body> |
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.
Conclusion
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
.