hasattribute() 是判断 html 属性是否存在的标准方法,返回布尔值,语义清晰、兼容性好(ie9+);需区分 attribute 与 property,避免混淆 checked 等布尔属性;不推荐用 getattribute() 或 jquery 的 prop() 做存在性判断。

直接用 hasAttribute() 方法最可靠,它专为这个目的设计,返回布尔值,语义清晰、兼容性好(IE9+ 支持)。
用 hasAttribute() 判断是否存在
这是标准、推荐的方式。传入属性名字符串,返回 true 或 false:
-
element.hasAttribute('disabled')→ 检查是否禁用 -
element.hasAttribute('data-id')→ 检查是否有自定义数据属性 -
element.hasAttribute('class')→ 即使 class 为空字符串也返回true
注意 attr 和 prop 的区别
不要混淆属性(attribute)和属性(property)。比如 checked:
-
input.hasAttribute('checked')检查 HTML 中是否写了checked="checked" -
input.checked获取的是当前实际勾选状态(布尔值),与 HTML 是否声明无关 - 对标准属性如
id、href、value,两者常一致;但对checked、selected等,行为不同
避免用 getAttribute() 做存在性判断
getAttribute() 返回属性值或 null,但不能直接靠真假值判断存在性:
-
getAttribute('disabled')可能返回""(空字符串)、"disabled"或null -
getAttribute('data-value') === null虽可行,但不如hasAttribute()直观且明确 - 尤其对布尔属性(如
disabled),HTML 中写disabled不带值时,getAttribute仍返回"",容易误判
jQuery 用户可选 attr() + undefined 判断
如果项目用 jQuery,可用 .attr() 结合 !== undefined:
-
$('#myBtn').attr('title') !== undefined表示有title属性 - 注意:不能用
== null,因为attr()对不存在属性返回undefined,不是null - 不建议用
.prop()判断属性存在性,它主要用于获取/设置 DOM 属性状态,不是 HTML 属性本身











