document.links 收錄文件中所有具有 href 的 <a> 與 <area> 元素。取 length 就是可點擊連結的總數。
<!DOCTYPE html> <html> <body> <img src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap"> <map name="planetmap"> <area shape="rect" coords="0,0,78,125" href="sun.htm" alt="Sun"> <area shape="circle" coords="88,60,5" href="mercury.htm" alt="Mercury"> <area shape="circle" coords="125,60,9" href="venus.htm" alt="Venus"> </map> <p><a href="/js/">JavaScript Tutorial</a></p> <p>連結數量: <script> document.write(document.links.length); </script> </p> </body> </html>
輸出:
Number of areas/links: 4
三個 <area> 加上一個 <a>,共 4 個。
<map> 搭配 <area> 是早期做「圖片熱區連結」的方式,缺點明顯:無法自適應縮放(coords 是絕對像素)、螢幕閱讀器難以理解、行動裝置上點擊區域精確度差。現在若要達到相同效果,建議改用 SVG 內嵌路徑,或用多個絕對定位的元素疊在圖片上(以百分比定位),兩者在無障礙與響應式上都好得多。
它仍常用於整頁層級的處理,例如外傳連結自動加上 target 與 rel:
for (var i = 0; i < document.links.length; i++) {
var a = document.links[i];
if (a.hostname && a.hostname !== location.hostname) {
a.target = '_blank';
a.rel = 'noopener noreferrer';
}
}
注意 document.links 只收錄有 href 的元素,所以錨點 <a name="x"> 不會被算進去;相對地,document.anchors 只收有 name 的 a。兩者範圍不同,別混用。若要更精確地選取,document.querySelectorAll('a[href]') 是語意最清楚的寫法。