JavaScript检查元素是否有指定属性|Element hasAttribute() 方法

元素对象参考手册


定义与用法

hasAttribute() 方法用于判断是否有指定的属性存在,如果存在返回 true,否则返回 false。

提示: 我们可以使用 setAttribute() 来添加一个新属性,或者修改元素中已存在的属性。


语法格式

element.hasAttribute( attributename)


示例代码

检查按钮元素是否有 onclick属性:

document.getElementsByTagName("BUTTON")[0].hasAttribute("onclick");

输出结果:

true

亲自试试


浏览器支持

方法Google ChromeInternet ExplorerFirefoxSafariOpera
hasAttribute()YesYesYesYesYes

所有主要浏览器都支持 hasAttribute() 方法

Internet Explorer 8 及更早 IE 版本不支持该方法。


参数说明

参数类型描述
attributenameString必须。你要检查的属性名。

返回值

类型描述
Boolean如果元素有属性返回 true, 否则返回 false。

技术细节

DOM 版本Core Level 2 Element Object

元素对象参考手册


相关