登录
首页 >  文章 >  前端

Element.getAttributeNames 获取所有属性方法详解

时间:2026-05-22 23:55:14 268浏览 收藏

本文揭穿了“Element.getAttributeNames”这一常见误解——它根本不是标准DOM API,而是开发者常因拼写错误或框架混淆而误用的伪方法;真正可靠的方式是通过Array.from(element.attributes).map(attr => attr.name)将原生的NamedNodeMap转换为数组来安全获取所有HTML声明的属性名,并详细解析了兼容性陷阱(如IE不支持展开运算符)、常见错误(如Object.keys失效)、过滤技巧(如提取data-属性)以及降级方案(for循环兼容老IE),帮助你避开坑、写出健壮且可维护的DOM属性处理代码。

如何用Element.getAttributeNames一键获取节点上所有的属性列表

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 是实时集合,包含所有属性节点(包括 classdata- 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)值为空字符串,不是 nullundefined
  • attributes 不包含通过 JS 设置的属性(如 el.id = 'x'),只反映 HTML 源码中声明的属性

想兼容更老环境?用 for 循环最稳

如果项目还要支持 IE9–IE10,Array.from 不可用,改用传统遍历:

const attrs = element.attributes;
const names = [];
for (let i = 0; i <p>性能影响几乎可以忽略,但逻辑清晰、无依赖、零兼容风险。</p><p>容易被忽略的一点:<br><code>attributes</code> 包含所有声明过的属性,哪怕值是空或非法(比如 <code><div class=></code> 也会有 <code>class</code> 属性节点)。别假设“没值就等于没这个属性”。</p><p>今天关于《Element.getAttributeNames 获取所有属性方法详解》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!</p>
资料下载
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>