Element.hasAttribute()

概述

hasAttribute 返回一个布尔值,指示该元素是否包含有指定的属性(attribute)。

语法

var result = element.hasAttribute(attName);
  • result 为返回的布尔值:truefalse
  • attName 是一个字符串,表示属性的名称。

例子

js
// 在为属性设置新值前检测该属性是否存在
var d = document.getElementById("div1");

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

备注

DOM methods dealing with element's attributes:

Not namespace-aware, most commonly used methods Namespace-aware variants (DOM Level 2) DOM Level 1 methods for dealing with Attr nodes directly (seldom used) DOM Level 2 namespace-aware methods for dealing with Attr nodes directly (seldom used)
setAttribute (DOM 1) setAttributeNS setAttributeNode setAttributeNodeNS
getAttribute (DOM 1) getAttributeNS (en-US) getAttributeNode getAttributeNodeNS
hasAttribute (DOM 2) hasAttributeNS - -
removeAttribute (DOM 1) removeAttributeNS removeAttributeNode -

规范