How to use javascript to get elements by class name?

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?

Introduction to the getElementsByClassName() method

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.

JavaScript getElementsByClassName() method examples

Let’s take some examples of using the getElementsByClassName() method.

Xem thêm: Sửa Lỗi Máy Lọc Nước Karofi Và Hướng Dẫn Xử Lý Các Lỗi Fil, Xử Lý Các Lỗi Thường Gặp Của Máy Lọc Nước Ro

Suppose that you have the following HTML document:


Code language: HTML, XML (xml)

1) Calling JavaScript getElementsByClassName() on an element example

The following example illustrates how to lớn use the getElementsByClassName() method lớn select the items which are the descendants of the element:


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:

Then, select elements, which are the descendants of the element, using the getElementsByClassName() method.Finally, create an array of the text content of elements by borrowing the map() method of the Array object.

2) Calling JavaScript getElementsByClassName() on the document example

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.

Summary

Use the JavaScript getElementsByClassName() method lớn select the child elements of an element that has one or more give class names.
*

*

The JavaScript Tutorial trang web helps you learn JavaScript programming from scratch quickly and effectively.