JavaScript: getElementsByClassName
getElementsByClassName() returns the elements that have a specified class, so a script can update a group at once.
What you will learn
- How to retrieve several elements by class
- How to loop through the returned collection
- Why the collection can reflect later DOM changes
Minimal example
<p class="status">Waiting</p>
<p class="status">Waiting</p>
<script>
const statuses = document.getElementsByClassName('status');
for (const status of statuses) status.textContent = 'Ready';
</script>The result is an HTMLCollection. It is array-like but is not a full Array, so use an appropriate loop or convert it when you need array methods.
Common mistakes
- Check whether the collection contains an element before indexing it.
- Be careful when adding or removing the class while iterating because the collection can be live.
- Use
querySelectorAllwhen you need more expressive selectors or a static NodeList.