document.images 收錄了頁面中所有的 img 元素,是一個按文檔順序排列的集合。取索引 0 就是首張圖片,之後可以讀取它的任意屬性。
<!DOCTYPE html>
<html>
<body>
<img id="klematis lilac" border="0" src="klematis.jpg" width="148" height="112">
<img id="klematis pink" border="0" src="klematis2.jpg" width="149" height="118">
<p>Id of first image:
<script>
document.write(document.images[0].id);
</script>
</p>
</body>
</html>
運行結果:
Id of first image: klematis lilac
id 中含空格不合規。示例中的 id="klematis lilac" 雖然瀏覽器能讀出來,但 HTML 規範中 id 不能包含空白字符,且 getElementById 也無法用它定位。實戰中請用連字符或下劃線。
使用前判空。頁面無圖時 document.images[0] 為 undefined:
var first = document.images[0];
if (first) { console.log(first.id); }
注意加載時機。如果 script 位於 head,執行時 body 尚未解析,集合會是空的。把腳本放到 body 末尾,或監聽 DOMContentLoaded。
更精確的定位方式。依賴「第一張」這種位置關係在頁面結構調整後很容易失效,能用具體選擇器時就不要靠索引:
document.querySelector('img'); // 第一個 img
document.getElementById('klematis'); // 按 id 精確定位
document.querySelectorAll('.banner img')[0]; // 限定範圍後再取
另外,images 集合只包含 img 元素,CSS 背景圖以及 <picture> 中的 source 都不在其中,統計圖片資源時需要另行處理。