Sometimes, we want to get element By using class name with JavaScript.
In this article, we’ll look at how to get element By using class name with JavaScript.
How to get element By using class name with JavaScript?
To get element By using class name with JavaScript, we can use the getElementsByClassName
method.
For instance, we write:
<div class='foo'>
</div>
<div class='foo'>
</div>
<div class='foo'>
</div>
to add 3 divs with class foo
.
Then we write:
const els = document.getElementsByClassName('foo')
console.log(els)
to call getElementsByClassName
with 'foo'
to return all the elements with class name foo
in an HTMLCollection object.
Conclusion
To get element By using class name with JavaScript, we can use the getElementsByClassName
method.