Summary: in this tutorial, you will learn how khổng lồ use the getElementsByClassName() method lớn select elements by class name.
Bạn đang xem: How to use javascript to get elements by class name?
The getElementsByClassName() method returns an array-like of objects of the child elements with a specified class name. The getElementsByClassName() method is available on the document element or any other elements.
When calling the method on the document element, it searches the entire document & returns the child elements of the document:
Code language: JavaScript (javascript)However, when calling the method on a specific element, it returns the descendants of that specific element with the given class name:
Code language: JavaScript (javascript)The method returns the elements which is a live HTMLCollection of the matches elements.
The names parameter is a string that represents one or more class names khổng lồ match; khổng lồ use multiple class names, you separate them by space.
Let’s take some examples of using the getElementsByClassName() method.
Suppose that you have the following HTML document:
Code language: HTML, XML (xml)
let thực đơn = document.getElementById("menu");let items = menu.getElementsByClassName("item");let data = <>.map.call(items, thành tích => item.textContent);console.log(data);
Code language: JavaScript (javascript)How it works:
To tìm kiếm for the element with the class heading-secondary, you use the following code:
let elements = document.getElementsByClassName("secondary");let data = <>.map.call(elements, elem => elem.textContent);console.log(data);
Code language: JavaScript (javascript)This example calls the getElementsByClassName() method on the document object. Therefore, it searches for the elements with the class secondary in the entire document.