Thuộc tính document.images trả về một **HTMLCollection** (tập hợp động) chứa tất cả các phần tử <img> trong tài liệu. Collection này tự động cập nhật khi thêm/xóa ảnh.
Cú pháp
document.images
Thuộc tính của Collection
| Thuộc tính | Mô tả |
|---|---|
| length | Số lượng phần tử <img> trong tài liệu. |
Phương thức của Collection
| Phương thức | Mô tả |
|---|---|
| [index] | Trả về phần tử <img> tại chỉ số index (bắt đầu từ 0). |
| item(index) | Tương tự [index], trả về phần tử tại chỉ số. |
| namedItem(name) | Trả về phần tử <img> có id hoặc name tương ứng. |
Ví dụ: Đếm số lượng ảnh trên trang
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; font-family: sans-serif; padding: 20px; }
img { margin: 10px; max-width: 150px; border: 1px solid #ddd; }
.btn {
background-color: #007bff; border: none; color: white;
padding: 10px 20px; border-radius: 25px; width: 60%;
margin: 20px auto; display: block; cursor: pointer;
}
.show { color: #dc3545; font-size: 2rem; font-weight: bold; margin-top: 15px; }
</style>
</head>
<body>
<h1>Ví dụ DOM Images Collection</h1>
<img src="https://www.tutorialspoint.com/spring/images/spring-mini-logo.jpg" alt="Spring">
<img src="https://www.tutorialspoint.com/hibernate/images/hibernate-mini-logo.jpg" alt="Hibernate">
<img src="https://www.tutorialspoint.com/sql/images/sql-mini-logo.jpg" alt="SQL">
<img src="https://www.tutorialspoint.com/plsql/images/plsql-mini-logo.jpg" alt="PL/SQL">
<button onclick="countImages()" class="btn">Đếm số ảnh</button>
<div id="result" class="show"></div>
<script>
function countImages() {
document.getElementById("result").textContent = document.images.length;
}
</script>
</body>
</html>
Kết quả
Trang có 4 ảnh:

Nhấn nút đếm:

💡 Mẹo:
document.imageslà **live collection** - tự động cập nhật khi DOM thay đổi.- Duyệt qua collection:
for (let img of document.images) { ... }. - Để lấy ảnh theo class/id: dùng
document.querySelectorAll()(trả về NodeList tĩnh).