Element.getAttributeNames 不是标准 API,正确方法是用 Array.from(element.attributes).map(attr => attr.name) 获取属性名,它返回 NamedNodeMap 需转换为数组处理。

Element.getAttributeNames 不存在,别被名字骗了
Element.getAttributeNames 这个方法根本不是标准 API。你搜到的可能是拼写错误、混淆了其他框架(比如某些 Vue 或 React 的调试工具),或者误把 Element.attributes 当成了返回字符串数组的方法。
浏览器原生 DOM 中,真正可用的是 Element.attributes——它返回一个 NamedNodeMap,不是数组,不能直接用 .map 或 .forEach,也不支持解构。
正确获取所有属性名:用 Array.from + attributes
最常用且兼容性好的写法是把 Element.attributes 转成数组,再提取 name:
const attrNames = Array.from(element.attributes).map(attr => attr.name);
说明:
-
element.attributes是实时集合,包含所有属性节点(包括class、data-<em> </em>、aria-等) -
Array.from()安全转换,兼容 IE11+ 和所有现代浏览器 - 不要用
[...element.attributes],IE 和旧版 Safari 不支持展开NamedNodeMap
常见错误现象:
- 直接调用
element.getAttributeNames()→ 报错TypeError: element.getAttributeNames is not a function - 用
Object.keys(element.attributes)→ 返回空数组(因为NamedNodeMap不是普通对象)
需要过滤或处理属性时,别漏掉这些细节
如果你只想要自定义 data- 属性,或排除某些内置属性,得手动筛:
const dataAttrNames = Array.from(element.attributes)
.filter(attr => attr.name.startsWith('data-'))
.map(attr => attr.name);注意点:
-
attr.name是小写的,即使 HTML 写的是DATA-ID,DOM 中也是data-id -
attr.value是字符串类型,空属性(如disabled)值为空字符串,不是null或undefined -
attributes不包含通过 JS 设置的属性(如el.id = 'x'),只反映 HTML 源码中声明的属性
想兼容更老环境?用 for 循环最稳
如果项目还要支持 IE9–IE10,Array.from 不可用,改用传统遍历:
const attrs = element.attributes;
const names = [];
for (let i = 0; i < attrs.length; i++) {
names.push(attrs[i].name);
}性能影响几乎可以忽略,但逻辑清晰、无依赖、零兼容风险。
容易被忽略的一点:attributes 包含所有声明过的属性,哪怕值是空或非法(比如 <div class=> 也会有 class 属性节点)。别假设“没值就等于没这个属性”。

















