Element: hasAttribute() メソッド

Element.hasAttribute() メソッドは、指定した要素が指定した属性を持つかどうかを示す論理値を返します。

構文

js
hasAttribute(name)

引数

name

属性の名前を示す文字列です。

返値

論理値です。

js
const foo = document.getElementById("foo");
if (foo.hasAttribute("bar")) {
  // do something
}

メモ

DOM メソッドは要素の属性を取り扱います。

名前空間に無関係、
最も一般的に使用されるメソッド
名前空間に限定される変数
(DOM Level 2)
Attr ノードを直接扱う DOM レベル 1 のメソッド
(ほとんど使用されない)
Attr ノードを直接扱う DOM レベル 2 名前空間に限定されるメソッド
(ほとんど使用されない)
setAttribute (DOM 1) setAttributeNS setAttributeNode setAttributeNodeNS
getAttribute (DOM 1) getAttributeNS getAttributeNode getAttributeNodeNS
hasAttribute (DOM 2) hasAttributeNS - -
removeAttribute (DOM 1) removeAttributeNS removeAttributeNode -

仕様書

Specification
DOM Standard
# ref-for-dom-element-hasattribute①

ブラウザーの互換性

BCD tables only load in the browser