How to get element by class name with JavaScript?

Sometimes, we want to get element by class name with JavaScript.

In this article, we’ll look at how to get element by class name with JavaScript.

How to get element by class name with JavaScript?

To get element by class name with JavaScript, we can use the getElementsByClassName method.

For instance, we write

const els = [...document.getElementsByClassName("foo")];

to call getElementsByClassName with 'foo' to return all the elements with class foo in a node list.

Then we spread the node list entries into an array with ...

Conclusion

To get element by class name with JavaScript, we can use the getElementsByClassName method.