HTML DOM hasAttribute()メソッド
❮要素オブジェクト例
<button>要素にonclick属性があるかどうかを確認します。
var x = document.getElementById("myBtn").hasAttribute("onclick");
以下の「自分で試してみてください」の例をもっと見てください。
定義と使用法
hasAttribute()メソッドは、指定された属性が存在する場合はtrueを返し、存在しない場合はfalseを返します。
ヒント: setAttribute()を使用して、新しい属性を追加するか、要素の既存の属性の値を変更します。
ブラウザのサポート
表の数字は、このメソッドを完全にサポートする最初のブラウザバージョンを示しています。
Method | |||||
---|---|---|---|---|---|
hasAttribute() | Yes | 9.0 | Yes | Yes | Yes |
構文
element.hasAttribute(attributename)
パラメーター
Parameter | Type | Description |
---|---|---|
attributename | String | Required. The name of the attribute you want to check if exists |
技術的な詳細
戻り値: | ブール値。要素に属性がある場合はtrueを返し、それ以外の場合はfalseを返します。 |
---|---|
DOMバージョン | コアレベル2要素オブジェクト |
その他の例
例
<a>要素にターゲット属性があるかどうかを調べます。その場合は、ターゲット属性の値を「_self」に変更します。
// Get the <a> element with id="myAnchor"
var x = document.getElementById("myAnchor");
// If the <a> element has a target attribute, set the value to "_self"
if (x.hasAttribute("target")) {
x.setAttribute("target", "_self");
}
関連ページ
HTMLチュートリアル:HTML属性
HTML DOMリファレンス:getAttribute()メソッド
HTML DOMリファレンス:removeAttribute()メソッド
HTML DOMリファレンス:setAttribute()メソッド
❮要素オブジェクト