To select elements by a given class name, you use the getElementsByClassName()
method:
let elements = document.getElementsByClassName('className');
Code language: JavaScript (javascript)
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>
Code language: HTML, XML (xml)
app.js
let elements = document.getElementsByClassName('note');
for (let i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}
Code language: JavaScript (javascript)
Output:
The first note.
The second note.
The third note.
Since the getElementsByClassName()
is a method of the Element
, you can select elements with a given class inside a container.
The following example shows only the innerHTML of the element with the CSS class note inside the container:
let container = document.getElementById('container');
let elements = container.getElementsByClassName('note');
for (let i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}
Code language: JavaScript (javascript)
Output:
The first note.
The second note.
Was this tutorial helpful ?