HTMLDOMドキュメントリンク
例
ドキュメント内のリンクの数:
let numb = document.links.length;
ドキュメントの最初のリンクのURLを取得します。
let url = document.links[0].href;
ドキュメントの最初のリンクのURLを取得します。
let url = document.links.item(0).href;
以下のその他の例。
定義と使用法
links
プロパティは、ドキュメント内のすべてのリンクのコレクションを返します。
forms
プロパティはHTMLCollectionを返します。
プロパティはlinks
読み取り専用です。
コレクション内のリンクは、href属性を持つ<a>要素と<area>要素を表します。
HTMLCollection
HTMLCollectionは、HTMLノードのコレクションです。
コレクション内のノードには、インデックス番号でアクセスできます。インデックスは0から始まります。
lengthプロパティは、コレクション内の要素の数を返します。
構文
document.links
プロパティ
Property | Description |
length | The number of 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オブジェクト。 ドキュメント内のすべての<a>および<area>要素。 要素は、ドキュメントに表示されるとおりに並べ替えられます。 |
その他の例
id = "myLink"で要素のURLを取得します。
let url = document.links.namedItem("myLink").href;
ドキュメントの最初のリンクに赤い境界線を追加します。
document.links[0].style.border = "5px solid red";
すべてのリンクをループして、それぞれのURL(href)を出力します。
const links = document.links;
let text = "";
for (let i = 0; i < links.length; i++) {
text += links[i].href + "<br>";
}
ブラウザのサポート
document.links
DOMレベル1(1998)の機能です。
すべてのブラウザで完全にサポートされています。
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |