Last updated: Apr 6, 2024
Reading time·2 min
To find all elements by className in React:
getElementsByClassName
method to get all elements with a specific
class.useEffect()
hook.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.
querySelectorAll
However, you could also use the document.querySelectorAll() method, to which you can pass a selector and not just a class name.
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
.
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;
If you need to find a single element, use the document.querySelector() method.
I've also written a tutorial on how to get an element by ID in React.