getElementsByClassName() trả về HTMLCollection (live collection), duyệt bằng vòng lặp for thông thường với index.
Ví dụ
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Duyệt getElementsByClassName</title>
</head>
<body>
<div class="demo">Chương trình JS đầu tiên</div>
<div class="demo">Chương trình thứ hai</div>
<div class="demo">Chương trình thứ ba</div>
<script>
var elements = document.getElementsByClassName('demo');
for (var i = 0; i < elements.length; i++) {
console.log(elements[i].innerHTML);
}
</script>
</body>
</html>
Cách chạy
Lưu index.html, mở Live Server, xem console.
Kết quả console
Chương trình JS đầu tiên
Chương trình thứ hai
Chương trình thứ ba
Lưu ý quan trọng: HTMLCollection là live - nếu DOM thay đổi, collection tự cập nhật. Không dùng for...of hoặc forEach trực tiếp (trừ khi convert: Array.from(elements)).