Find all elements by className in React

avatar

Borislav Hadzhiev

Mon Apr 18 20222 min read

banner

Photo by Yaro Felix

Find all elements by className in React #

To find all elements by className in React:

  1. Use the getElementsByClassName method to get all elements with a specific class.
  2. Place your call to the method in the useEffect() hook.
App.js
import {useEffect} from 'react'; const App = () => { useEffect(() => { const allWithClass = Array.from( document.getElementsByClassName('example') ); console.log(allWithClass); }, []); return ( <div> <div> <h2 className="example">Alice</h2> <h2 className="example">Bob</h2> <h2 className="example">Carl</h2> </div> </div> ); }; export default App;

We passed an empty dependencies array to the useEffect hook, so it is only going to run when the component mounts.

We used the document.getElementsByClassName method to select all elements that have the example class on the page.

However, you could also use the document.querySelectorAll method, to which you can pass a selector and not just a class name.

App.js
import {useEffect} from 'react'; const App = () => { useEffect(() => { const allWithClass = Array.from( document.querySelectorAll('h2.example') ); console.log(allWithClass); }, []); return ( <div> <div> <h2 className="example">Alice</h2> <h2 className="example">Bob</h2> <h2 className="example">Carl</h2> </div> </div> ); }; export default App;

We passed a selector to the querySelectorAll method. The example above selects all h2 elements on the page that have a class of example.

We used the Array.from method to convert the collection into an array. However, this might not be necessary for your use case.

You can iterate over the array of elements and perform operations on each. Here is an example that changes the background color of each h2 element that has a class of example.

App.js
import {useEffect} from 'react'; const App = () => { useEffect(() => { const allWithClass = Array.from( document.querySelectorAll('h2.example') ); console.log(allWithClass); allWithClass.forEach(element => { element.style.backgroundColor = 'salmon'; }); }, []); return ( <div> <div> <h2 className="example">Alice</h2> <h2 className="example">Bob</h2> <h2 className="example">Carl</h2> </div> </div> ); }; export default App;
Use the search field on my Home Page to filter through my more than 1,000 articles.