There are different methods that you can use to get DOM elements. In this shot we are going to use document.getElementByClassName()
, which returns a collection of DOM elements that have the same specified class name.
If the method does not find any element in DOM with the specified class name, then it returns null
.
var elements = document.getElementsByClassName(class_name);
getElementByClassName(ClassName)
takes a parameter of type string
. ClassName is given to the HTML elements that can get different DOM elements. The same class name can be given to different elements. In the code below, we assign a class name to an element.
<p class="Test"></p>
In the <p>
HTML tag above, we use the class attribute to assign a class name. class names are case-sensitive, which means “Test”
and “test”
are different classes. Check the code below to get the <p>
element:
//correctvar element = document.getElementsByClassName("Test");//wrong "test" should be "Test"var element = document.getElementsByClassName("test");
Now, we will try to use the getElementByClassName()
method to change the color of elements with the click of a button.
The HTML page only has three elements: two paragraphs and a button tag with the same class name. The task is to change the color of both paragraph elements when we click on the button.
In the code above:
In line 1, we use document.getElementByClassName('first')
to get the elements. first
is the class name given to both <p>
elements. The method returns objects of all elements and stores them in a variable named element
.
In line 4, we have a function, change()
, which will be called when we click on the button.
In line 5, we use a for
loop to change the color of all elements in the variable element
, which is an object containing all the elements with the same class name.
In line 7, we use the element object to change the element property. We use element[i].style.color
(i
is the index of element). element
is the object that has the style property. style
has several properties, one of which is color.
Check the console output. It will return an object of size 2, which means it has both elements with the same class. With a click of the button, we are able to change the color of both elements.