ภาพเอกสาร HTML DOM
ตัวอย่าง
จำนวน <img> องค์ประกอบในเอกสาร:
document.images.length;
วนซ้ำทุกองค์ประกอบ <img> และส่งออก URL (src) ของแต่ละองค์ประกอบ:
const myImages = document.images;
let text = "";
for (let i = 0; i < myImages.length; i++) {
text += myImages[i].src + "<br>";
}
URL ขององค์ประกอบ <img> แรกคือ:
document.images[0].src;
URL ขององค์ประกอบ <img> แรกคือ:
document.images.item(0).src;
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
คุณสมบัติimages
ส่งคืนคอลเลกชันขององค์ประกอบ <img> ทั้งหมดในเอกสาร
คุณสมบัติส่งimages
คืนHTMLCollection
คุณสมบัติimages
เป็นแบบอ่านอย่างเดียว
บันทึก
คุณสมบัติimages
ไม่ส่งคืนองค์ประกอบ <input> ด้วย type="image"
ดูสิ่งนี้ด้วย:
HTMLCollection
HTMLCollection คือ ชุดของโหนด HTML
โหนดในคอลเล็กชันสามารถเข้าถึงได้ด้วยหมายเลขดัชนี ดัชนีเริ่มต้นที่ 0
คุณสมบัติความยาวส่งคืนจำนวนองค์ประกอบในคอลเลกชัน
ไวยากรณ์
document.images
คุณสมบัติ
Property | Description |
length | The number of <img> elements in the collection. |
วิธีการ
Method | Description |
[index] | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
item(index) | Returns the element with the specified index (starts at 0). Returns null if the index is out of range. |
namedItem(id) | Returns the element with the specified id. Returns null if the id does not exist. |
คืนมูลค่า
พิมพ์ | คำอธิบาย |
วัตถุ | วัตถุ HTMLCollection องค์ประกอบ <img> ทั้งหมดในเอกสาร องค์ประกอบจะถูกจัดเรียงตามที่ปรากฏในเอกสาร |
ตัวอย่างเพิ่มเติม
URL ขององค์ประกอบ <img> ที่มี id="myImg" คือ:
document.images.namedItem("myImg").src;
เพิ่มเส้นขอบสีดำให้กับองค์ประกอบ <img> แรก:
document.images[0].style.border = "10px dotted black";
รองรับเบราว์เซอร์
document.images
เป็นคุณลักษณะ DOM ระดับ 1 (1998)
ได้รับการสนับสนุนอย่างเต็มที่ในเบราว์เซอร์ทั้งหมด:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |