Metodo ng getElementsByClassName() ng HTML DOM Document

Definasyon at Gagamit

getElementsByClassName() Ang metoda ay binabalik ang koleksyon ng mga elemento na may tinukoy na klase.

getElementsByClassName() Ang metoda ay binabalik HTMLCollection.

getElementsByClassName() Ang atrubuto ay walang basahin.

HTMLCollection

HTMLCollection Ito ay katulad ng listahan ng HTML elemento (collection).

Maaaring mapagamit ang index upang makapasok sa mga elemento sa koleksyon (mula 0).

length Ang atrubuto ay binabalik ng bilang ng mga elemento sa koleksyon.

Mga iba pang panggalingan ng impormasyon:

Metodo ng getElementById()

Metodo ng getElementsByTagName()

Metodo ng querySelector()

Metodo ng querySelectorAll()

Objeto ng HTMLCollection

Eksemplo

Talakayan 1

Nakakuha ng lahat ng mga elemento na may class="example":

const collection = document.getElementsByClassName("example");

Try It Yourself

Talakayan 2

Nakakuha ng lahat ng mga elemento na may "example" at "color" klase:

const collection = document.getElementsByClassName("example color");

Try It Yourself

Example 3

Number of elements with class="example":

let numb = document.getElementsByClassName("example").length;

Try It Yourself

Example 4

Change the background color of all elements with class="example":

const collection = document.getElementsByClassName("example");
for (let i = 0; i < collection.length; i++) {
  collection[i].style.backgroundColor = "red";
}

Try It Yourself

Syntax

document.getElementsByClassName("classname)

Parameter

Parameter Description
classname

Required. The class name of the element.

Retrieve multiple class names separated by spaces, for example "test demo".

Return Value

Type Description
Object

HTMLCollection Object.

Collection of elements with specified class names.

Sort elements in the order they appear in the document.

Browser Support

document.getElementsByClassName() It is a DOM Level 1 (1998) feature.

All Browsers Support It:

Chrome IE Edge Firefox Safari Opera
Chrome IE Edge Firefox Safari Opera
Support 9-11 Support Support Support Support

Related Pages

CSS Tutorial:CSS Grammar

CSS Reference Manual:CSS .class Selector

HTML DOM Reference Manual:element.getElementsByClassName()

HTML DOM Reference Manual:className Attribute

HTML DOM Reference Manual:classList Attribute

HTML DOM Reference Manual:Style Object