How to Get Elements by Class Name in JavaScript
JavaScript is one of the most popular and widely used scripting languages in the world. It adds interactivity to the web page. Therefore, it is often necessary to get the elements that are available in the Document Object Model (DOM) of an HTML page. In this article, you will learn how to get all the elements in the document based on the class name.
There are three possible ways to access the elements. They are,
- getElementById()
- getElementsByClassName()
- getElementsByTagName()
Syntax: document.getElementByClassName(classname)
Parameter: classname
Type: String
Description: This is a required parameter. You need to pass the class name of the element you want to return, as the parameter.
The following example illustrates the use of this method to customize styles for specific elements defined using the class name "color". In this example, JavaScript code is embedded with the HTML file. Check the previous guide to learn more about how to link JavaScript to HTML.
The following code snippet uses this method to get the total number of defined elements using the "sample" class name and saves it in the variable "count".
let count = document.getElementsByClassName("sample").length;
If you want to access elements with multiple class names, use the following syntax.
Syntax: document.getElementByClassName(classname separated with space)
I hope that you all have understood how to use the getElementsByClassName method. See you all soon with more exciting content.
Visit the previous guide about how to round in Python.
Author of Get Basic Idea / Undergraduate at University of Moratuwa.