Using the getElementsByClassName() method in JavaScript

The getElementsByClassName() method returns an array of elements in a document that have a class name of a value we specify when using the method. It can be used to manipulate more than one element (eg. change their contents or appearance) or get information from more than one element in a document that has a specified class name (unlike the getElementById method which is only used to return one element with a unique ID).

The getElementsByClassName() method searches through an entire HTML document and looks for elements that have the class name we specify as the parameter between the quotation marks. The syntax of the method looks like this:

 document.getElementsByClassName('class_name_goes_here');

Watch the video below or scroll down to view the sample code.

Sample HTML code (index.html file):

<html>
    <head>
        <title>Using the document.getElementsByClassName() method</title>
        <script src="script.js"></script>
    </head>

    <body>
        <p class="mytext">Click the button</p>
        <p class="mytext">Click the button</p>
        <p class="mytext">Click the button</p>
        <p class="mytext">Click the button</p>

        <button onclick="changeText();">Click me!</button>
    </body>
</html>

Sample JavaScript code (script.js file):

Working with just one element:

In the example below, we use the getElementsByClassName() method to return an array of all elements in the HTML document that have the ‘mytext‘ class name. In this example, we are just modifying the innerHTML of the first element (mytext[0]) . The first element will be index 0 in the array (eg. mytext[0]), the second element will be index 1 (eg. mytext[1]), and so on…).

function changeText(){
    var mytext = document.getElementsByClassName('mytext');
    mytext[0].innerHTML = "You clicked the button!";
}
Working with more than one element:

In this example, we are using a for loop to work through the array of elements and modify the innerHTML of all the paragraph elements with the class name ‘mytext‘ as well as changing their colour to green.

function changeText(){
    var mytext = document.getElementsByClassName('mytext');
    for(var i = 0; i < mytext.length; i++){
        mytext[i].innerHTML = "You clicked the button!";
        mytext[i].style.color = "green";
    }
}

Next tutorial: Changing an image using getElementById() method