Menu
Coddy logo textTech

getElementsByClassName

Lesson 5 of 13 in Coddy's JavaScript DOM Methods course.

The function getElementsByClassName() returns an array of all elements with a matching class attribute, useful for selecting multiple elements that share the same style or behavior. For example:

const elements = document.getElementsByClassName("className");

The above retrieves the elements with a class of className and saves them to a variable called elements.

We have to iterate over this variable to change the properties of all similar elements, for example:

for (const element of elements) {
	className.style.color = "blue";
	className.style.fontWeight = "bolder";
}
challenge icon

Challenge

Easy

You are given HTML code that contains paragraphs with a class name highlight.

Using JavaScript only, change the color and font weight of the text :

  1. Retrieve the elements using getElementsByClassName() function.
  2. Iterate over this retrieved element variable using a for loop.
  3. Modify the color to “orange” and the fontWeight  to “bold” using style property, to every element in the array.

You will need to refresh the web page in order to see the changes:

Try it yourself

<!DOCTYPE html>
<html>
    <body>
        <p class="highlight">Text 1</p>
        <p class="highlight">Text 2</p>
        <script src="script.js"></script>
    </body>
</html>

All lessons in JavaScript DOM Methods