JavaScript get element by class | Simple example code

You need to use the document.getElementsByClassName(‘class_name’) to get element by class in JavaScript. It gets the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)

Example of How to get element by class name

HTML example of Get all elements with the specified class name using getElementsByClassName method in JavaScript.

Don’t forget that the returned value is an array of elements so if you want the first one use:

Complete example code

Output:

JavaScript get element by class HTML

Do comment if you have any doubts and suggestion son this tutorial.

Note: All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.