getElementsByClassName() method

Coding with JavaScript

🕑 This lesson will take about 10 minutes

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 & JavaScript code - example 1

In this example, the innerHTML of the first element that belongs to the ‘mytext’ class will be modified. This is achieved my referencing the class name and then using indexing to reference an element that uses that class. Indexing starts at 0, so the first element that belongs to a class will have an index of 0. When clicking the button, only the first paragraph will be modified.

Sample HTML & JavaScript code - example 2

In this example, we are using a for loop to work through each paragraph element that belongs to the class with the name ‘mytext’, and modify the innerHTML of all the paragraph elements with that class name as well as changing their colour to green. As you can see, when clicking the button, all paragraph elements are modified.

Next lesson: querySelector() method