JavaScript GetElementsByClassName() method

The getElementsByClassName() method is used for selecting or getting the elements through their class name value. It is used when you want to get all the elements with the specified class name.


var ele=document.getELementsByClassName('classname');  

classname‘: It is the string that specifies either a single classname or multiple class names to match. This is the mandatory argument to be passed. To search for multiple class names, separate them with spaces, like “test demo”.

Return Value

HTMLCollection: It is a collection of all elements in the document with the specified class name.

  • The HTMLCollection object represents a collection of nodes.
  • The nodes can be accessed by index numbers.
  • The index starts at 0.
  • length property of the HTMLCollection object is used to determine the number of elements with a specified class name. This is useful when you want to loop through all elements and extract the info you want.


<!DOCTYPE html>
<html lang="en">

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript GetElementsByClassName() method Example</title>


        <div class="example">First div element with class="example".</div>

        <div class="example">Second div element with class="example".</div>

        <div class="example">Third div element with class="example".</div>

        <p>Click the button to change the text of the first div element with class="example" (index 0).</p>

        <button onclick="myFunction()">Try it</button>

            function myFunction() {
                var x = document.getElementsByClassName("example");
                x[0].innerHTML = "Hello World!";
                x[1].innerHTML = "Changed second div too!";


JavaScript GetElementsByClassName() method Example – Output
JavaScript GetElementsByClassName() method Example – Output After clicking try it button.