คุณสมบัติ document.images คืนค่า HTMLCollection ของอิลิเมนต์ <img> ทั้งหมดในเอกสาร ใช้จัดการรูปภาพหลายรูปพร้อมกัน
รูปแบบ (Syntax)
document.images
คุณสมบัติของ Images Collection
| คุณสมบัติ | คำอธิบาย |
|---|---|
| length | คืนค่าจำนวนรูปภาพ <img> ในเอกสาร |
เมธอดของ Images Collection
| เมธอด | คำอธิบาย |
|---|---|
| [index] | คืนค่ารูปภาพที่ index ที่ระบุ (0-based) |
| item(index) | คืนค่ารูปภาพที่ index ที่ระบุ (เหมือน [index]) |
| namedItem(id) | คืนค่ารูปภาพที่มี id ตรงกับที่ระบุ |
ตัวอย่างการใช้งาน
นับจำนวนรูปภาพในหน้าเว็บ:
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; }
.btn { background-color: lightblue; border: none; height: 2rem; border-radius: 50px; width: 60%; margin: 1rem auto; display: block; }
.show { color: #db133a; font-size: 2rem; font-weight: bold; }
</style>
</head>
<body>
<h1>ตัวอย่าง DOM Images Collection</h1>
<img src="https://www.tutorialspoint.com/spring/images/spring-mini-logo.jpg" alt="Learn Spring">
<img src="https://www.tutorialspoint.com/hibernate/images/hibernate-mini-logo.jpg" alt="Learn Hibernate">
<img src="https://www.tutorialspoint.com/sql/images/sql-mini-logo.jpg" alt="Learn SQL">
<img src="https://www.tutorialspoint.com/plsql/images/plsql-mini-logo.jpg" alt="Learn PL/SQL">
<button onclick="getCount()" class="btn">นับจำนวนรูปภาพ</button>
<div class="show"></div>
<script>
function getCount() {
document.querySelector('.show').innerHTML = document.images.length;
}
</script>
</body>
</html>
การใช้งานขั้นสูง
วนลูปเพื่อ lazy load รูปภาพทั้งหมด:
for (var i = 0; i < document.images.length; i++) {
var img = document.images[i];
if (img.dataset.src) {
img.src = img.dataset.src; // โหลดจริงเมื่อต้องการ
}
}
หาภาพโดย id:
var logo = document.images.namedItem("logo"); // ต้องมี id="logo"