JavaScript HTML DOM 集合

Objek HTMLCollection

getElementsByTagName() Method kembalikan HTMLCollection Objek.

Objek HTMLCollection adalah senarai objek HTML seperti array (kumpulan).

Kod di bawah ini memilih semua elemen <p> didalam dokumen:

Example

var x = document.getElementsByTagName("p");

Elemen dalam kumpulan ini dapat diakses melalui nombor indeks.

Untuk mengakses elemen <p> kedua, anda boleh menulis seperti berikut:

y = x[1];

Try It Yourself

Keterangan:Indeks bermula daripada 0.

Panjang HTML HTMLCollection

length Pertubuhan mendefinikan jumlah elemen dalam HTMLCollection:

Example

var myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = myCollection.length; 

Try It Yourself

Example Explanation:

  • Create a collection of all <p> elements
  • Displays the length of the collection

length Properties are useful when you need to iterate over elements in a collection:

Example

Change the background color of all <p> elements:

var myCollection = document.getElementsByTagName("p");
var i;
for (i = 0; i < myCollection.length; i++) {
    myCollection[i].style.backgroundColor = "red";
}

Try It Yourself

HTMLCollection is not an array!

HTMLCollection may look like an array, but it is not an array.

You can iterate over the list and access elements by numeric reference (like an array).

However, you cannot use array methods on HTMLCollection, such as valueOf()pop()push() or join().