定義と使い方
該当する要素に指定した属性の値を取得するには、getAttribute()関数を使用してください。
構文
element.hasAttribute(attributeName)
引数
attributeName |
必須。要素が持っているかどうかを確認する属性の名前(文字列形式)です。 |
|---|
戻り値
該当する要素が指定した属性を持っていればtrueを返し、持っていなければfalseを返します。
基本例
<video src="video.mp4" autoplay></video>
const myVideo = document.querySelector("video");
console.log(myVideo.hasAttribute("src")); // true
console.log(myVideo.hasAttribute("autoplay")); // true
console.log(myVideo.hasAttribute("loop")); // false
コードの補足説明querySelector()関数は、指定したCSSセレクタと一致する最初の要素オブジェクトを返します。
活用例
hasAttribute()関数は、主に該当する要素に属性があるかどうかを確認する条件文でよく使用されます。
次は、Webサイト上にあるリンク(<a>タグ)のすべての要素を取得し、新しいウィンドウで開くように変更する活用例です。
<a href="https://example.com">example.com</a>
<a href="https://example.com">example.com</a>
<a href="https://example.com">example.com</a>
// ドキュメント内のすべてのa要素を取得
const anchorEle = document.querySelectorAll("a");
// それぞれの要素を順番に処理する - forEach()関数を適用
anchorEle.forEach(ele => {
// href属性がある場合
if (ele.hasAttribute("href")) {
// 新しいウィンドウで開くリンクに変更
ele.setAttribute("target", "_blank");
// 新しいウィンドウで開く際のセキュリティに関するrel属性の値を設定
ele.setAttribute("rel", "noopener noreferrer");
}
});
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
example.com
</a>
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
example.com
</a>
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
example.com
</a>
活用例で使用した関数や概念については、以下の関連トピックのリンクを参照してください。
ブラウザーの互換性
| メソッド |
デスクトップ Chrome
|
デスクトップ Edge
|
デスクトップ Firefox
|
Safari
|
|---|---|---|---|---|
hasAttribute()
|
1 | 12 | 1 | 1 |
仕様書
| 仕様書 | |
|---|---|
hasAttribute()
|
DOM Standard #ref-for-dom-element-hasattribute① |