To select elements by a given class name, you use the getElementsByClassName()
method:
let elements = document.getElementsByClassName('className');
The getElementsByClassName()
method returns a collection of elements whose class name is the CSS class that you pass into the method. The return collection is a NodeList
.
HTML
<html>
<head>
<title>JavaScript getElementsByClassName() example</title>
</head>
<body>
<div id="container">
<p class="note">The first note.</p>
<p class="note">The second note.</p>
</div>
<p class="note">The third note.</p>
<script src="js/app.js"></script>
</body>
</html>
app.js
let elements = document.getElementsByClassName('note');
for (let i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}
Output
The first note.
The second note.
The third note.
Source
https://www.javascripttutorial.net/dom/selecting/selecting-elements-by-class-name/