Element.attributes 返回 NamedNodeMap,是 XML 节点自身属性的集合;它支持索引访问和 getNamedItem(),但非数组、不保证顺序,且不包含命名空间声明的语义解析。

用 Element.attributes 获取 XML 节点的所有属性集合
HTML5 中通过 DOMParser 解析 XML 字符串后,得到的是标准的 Element 对象,其 attributes 属性返回一个 NamedNodeMap —— 这就是你要的“属性集合”。它不是数组,但可按索引访问,也支持 getNamedItem() 查找。
-
attributes只包含该元素自身的属性,不含命名空间声明(如xmlns)或默认属性 - 遍历时注意:IE 以外的现代浏览器中,
attributes包含所有属性(包括id、class等),但不保证顺序 - 若需兼容老版本 Edge 或 IE,应改用
getAttributeNames()(仅支持现代浏览器)或手动遍历attributes.length
遍历 attributes 的两种可靠写法
推荐使用传统索引遍历,兼容性最好;for...of 在部分环境(如某些 Electron 内核)中对 NamedNodeMap 支持不稳定。
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(' ', 'application/xml');
const book = xmlDoc.querySelector('book');
// ✅ 推荐:用 length + 索引遍历
for (let i = 0; i < book.attributes.length; i++) {
const attr = book.attributes[i];
console.log(attr.name, attr.value); // "id" "123", "lang" "zh", "data-status" "draft"
}
// ⚠️ 注意:以下写法在 Safari 15.6 之前或旧版 Chromium 中可能报错
// for (const attr of book.attributes) { ... }
getAttributeNames() 更简洁但有兼容限制
如果只关心属性名列表(比如做白名单校验),getAttributeNames() 返回字符串数组,语义清晰、写法干净,但不支持 IE 和 Safari ≤14.1。
- 返回值是纯
Array,可直接用map、filter处理 - 它不返回属性节点对象,无法获取
attr.specified或命名空间前缀信息 - 对自定义属性(
data-*)、标准属性一视同仁,无过滤逻辑
if (book.getAttributeNames) {
const names = book.getAttributeNames(); // ["id", "lang", "data-status"]
names.forEach(name => {
console.log(name, book.getAttribute(name));
});
} else {
// fallback 到 attributes.length 方式
}
XML 中 namespace-aware 属性需要额外处理
如果你解析的是带命名空间的 XML(如 ),attributes 仍能读取到 xmlns:ns,但它的 name 是 xmlns:ns,value 是 URI;而 getAttributeNames() 在多数浏览器中会忽略这类声明属性。
立即学习“前端免费学习笔记(深入)”;
- 要提取命名空间绑定,必须走
attributes遍历,并检查attr.name.startsWith('xmlns') -
attr.namespaceURI对普通属性为null,对命名空间声明则为"http://www.w3.org/2000/xmlns/" - 不要依赖
getAttribute('xmlns:ns')—— 它在很多浏览器中返回null,即使属性存在
attributes 不是数组、没处理命名空间声明、或者在需要兼容时误用了 getAttributeNames()。










