Skip to content

JavaScript get element by class | Simple example code

  • by

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:

document.getElementsByClassName('class_name')[0]

Complete example code

<!DOCTYPE html>
<html>
<body>

    <p class="test">Hello </p>

    <script>

      var tests = document.getElementsByClassName('test')[0];
      alert(tests);
      
  </script>

</body>
</html>

Output:

JavaScript get element by class HTML

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

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading