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
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 :
Retrieve the elements using getElementsByClassName() function.
Iterate over this retrieved element variable using a for loop.
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: