萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 取得頁面第一張圖片 ID:document.images[0].id 完整教學

前言

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

document.images 詳細特性

特性說明
元素類型<img> (不含 <picture>, <svg>, CSS 背景圖)
集合類型HTMLCollection (即時、類陣列)
順序文檔順序 (DFS)
長度document.images.length
索引存取document.images[i]
名稱存取document.images['nameOrId']

進階操作範例

1. 取得所有圖片 src 陣列 (用於預載/圖庫)

const srcs = Array.from(document.images).map(img => img.src);
console.log(srcs);

2. 為所有無 alt 的圖片補上預設替代文字

Array.from(document.images).forEach(img => {
  if (!img.alt) img.alt = '圖片說明';
});

3. 懶加載觸發:將 data-src 移至 src

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));

4. 動態新增圖片自動偵測

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 vs querySelectorAll('img')

特性document.imagesdocument.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 中 (屬於表單元素)。
  • 跨域 iframe 內圖片**不包含**在父頁面集合中。
  • 即時集合迴圈中修改 DOM (如刪除圖片) 會導致索引錯位,**務必轉陣列**:Array.from(document.images).forEach(...)。

總結

document.images[0].id 即時取得第一張 <img> 的 ID。理解 HTMLCollection 即時性、<input type=image> 不包含、跨域隔離等特性,配合 Array.from 安全遍歷。現代專案圖片相關操作 (懶加載、預載、觀察) 建議改用 IntersectionObserver + querySelectorAll,語意更清晰、效能更可控。

copyright © 萬盛學電腦網 all rights reserved