document.images 回傳文檔中所有 <img> 元素組成的 **HTMLCollection** (即時集合)。本文示範取得第一張圖片 ID、遍歷所有圖片、動態監控與現代替代方案。
const firstImgId = document.images[0]?.id; // 可選鏈防無圖片報錯
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>第一張圖片 ID</title>
</head>
<body>
<img id="klematis_lilac" src="klematis.jpg" width="148" height="112">
<img id="klematis_pink" src="klematis2.jpg" width="149" height="118">
<p>第一張圖片 ID:<span id="output"></span></p>
<script>
const firstImg = document.images[0];
document.getElementById('output').textContent = firstImg ? firstImg.id : '無圖片';
</script>
</body>
</html>
輸出:klematis_lilac
| 特性 | 說明 |
|---|---|
| 元素類型 | <img> (不含 <picture>, <svg>, CSS 背景圖) |
| 集合類型 | HTMLCollection (即時、類陣列) |
| 順序 | 文檔順序 (DFS) |
| 長度 | document.images.length |
| 索引存取 | document.images[i] |
| 名稱存取 | document.images['nameOrId'] |
const srcs = Array.from(document.images).map(img => img.src);
console.log(srcs);
Array.from(document.images).forEach(img => {
if (!img.alt) img.alt = '圖片說明';
});
const lazyImages = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.removeAttribute('data-src');
observer.unobserve(img);
}
});
});
lazyImages.forEach(img => observer.observe(img));
let lastCount = document.images.length;
new MutationObserver(() => {
const current = document.images.length;
if (current > lastCount) {
for (let i = lastCount; i < current; i++) {
console.log('新圖片:', document.images[i].src);
}
lastCount = current;
}
}).observe(document.body, { childList: true, subtree: true });
| 特性 | document.images | document.querySelectorAll('img') |
|---|---|---|
| 集合類型 | HTMLCollection (即時) | NodeList (靜態快照) |
| 支援 for...of | 否 (需 Array.from) | 是 |
| 名稱/ID 索引 | 支援 images['id'] | 不支援 |
| 包含 picture/source | 否 | 否 (需 'picture source, img') |
| 效能 | 極快 (瀏覽器內建維護) | 查詢時遍歷 DOM |
id 為空字串時 .id 回傳 "",請用 || '無ID' 處理顯示。<input type="image"> **不包含**在 document.images 中 (屬於表單元素)。Array.from(document.images).forEach(...)。document.images[0].id 即時取得第一張 <img> 的 ID。理解 HTMLCollection 即時性、<input type=image> 不包含、跨域隔離等特性,配合 Array.from 安全遍歷。現代專案圖片相關操作 (懶加載、預載、觀察) 建議改用 IntersectionObserver + querySelectorAll,語意更清晰、效能更可控。