English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
getElementsByClassName()The method can obtain elements with the specified class attribute value, and the return value is a collection.
The elements in the returned list are sorted in the order they appear in the source code.
The returned list can be accessed by index number. The index starts from 0.
Using the arraylengthThe property determines the number of elements with the specified class name, and then all elements can be traversed to extract the required information.
document.getElementsByClassName(class)
var x = document.getElementsByClassName("demo");Test and See‹/›
The getElementsByClassName() method is fully supported by all browsers:
Method | |||||
getElementsByClassName() | Is | Is | Is | Is | Is |
Parameter | Description |
---|---|
class | A string representing the class name of the element to be obtained. To search for multiple class names, separate them with spaces, for example, 'demo color'. |
Return value: | Returns an array-like object of all child elements with the given class names. |
---|---|
DOM Version: | DOM Level1 |
Use the "demo" and "color" classes to get all elements:
var x = document.getElementsByClassName("demo color");Test and See‹/›
Use class="demo" to change the background color of all elements:
var x = document.getElementsByClassName("demo"); for (let i = 0; i < x.length; i++) { x[i].style.backgroundColor = "coral"; }Test and See‹/›
DOM Document querySelector()Methods
DOM Document querySelectorAll()Methods
DOM Document getElementById()Methods
DOM Document getElementsByTagName()Methods