Sometimes, we want to get elements from a HTMLCollection with JavaScript.
In this article, we’ll look at how to get elements from a HTMLCollection with JavaScript.
How to get elements from a HTMLCollection with JavaScript?
To get elements from a HTMLCollection with JavaScript, we can access them by their index.
For instance, we write:
<div class='review'>
</div>
<div class='review'>
</div>
to add elements with a class.
Then we write:
const els = document.getElementsByClassName('review');
console.log(els[0])
to call getElementsByClassName
with 'review'
to select elements with class review
.
Then we can get the first one in the collection with els[0]
.
Conclusion
To get elements from a HTMLCollection with JavaScript, we can access them by their index.