element.hasAttribute

概要

hasAttribute

は指定の要素が指定の属性を持つか否かを示す真偽値を返します。

構文

var result = element.hasAttribute(attName);
  • result : true または false の戻り値を保有
  • attName : 属性の名前を表す文字列を指定

対象属性の存在をチェックし、無い場合にのみ属性を設定する例を以下に示します。

var d = document.getElementById("div1"); // 対象要素を取得

if ( !d.hasAttribute("align") ) {
  d.setAttribute("align", "center");
}

注記

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 -

仕様書