Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
可能重复: 使用 Javascript/jQuery 从 HTML 元素中获取所有属性
我需要检索 DOM 元素的所有属性。方法我看过getAttribute(),但事先不知道属性的名称。如果我getElementById()用来检索一个元素,那么我如何访问该元素的所有属性及其值?
getAttribute()
getElementById()
每个 DOM 节点都有一个attributes属性,它是一个 NamedNodeMap(本质上是一个具有一些额外功能的数组)。特别是这意味着您可以获取elem.attributes.length并循环通过它们。
attributes
elem.attributes.length
每个单独的属性都是一个 Attr 对象,它具有(除其他外)name和value属性。
name
value
请注意,IE7 及以下版本有一个可能定义的所有属性的列表(总共 84 个),无论它们实际上是否在元素上。在实际包含属性值之前,您可能希望快速检查虚假值。