Element:getAttributeNames() 方法
Element 接口的 getAttributeNames() 方法返回该元素的属性名,结果是一个字符串组成的 Array。如果元素没有任何属性,则返回一个空数组。
使用 getAttributeNames() 配合 getAttribute(),是访问 Element.attributes 的一种更节省内存且性能更好的替代方法。
getAttributeNames() 返回的名称是限定名称,这意味着带有命名空间前缀的属性会以其命名空间前缀(而不是实际的命名空间)和冒号,后跟属性名(例如 xlink:href)的形式返回,而任何没有命名空间前缀的属性则会原样返回(例如 href)。
语法
js
getAttributeNames()
参数
无。
返回值
一个由字符串组成的 (Array)。
示例
以下示例显示了如何操作
- 对于带有命名空间前缀的属性,
getAttributeNames()会返回该命名空间前缀和属性名。 - 对于没有命名空间前缀的属性,
getAttributeNames()会原样返回该属性名。
理解这一点很重要
- 一个属性可能在 DOM 中存在命名空间但没有命名空间前缀。
- 对于 DOM 中存在命名空间但缺少命名空间前缀的属性,
getAttributeNames()将仅返回属性名,而不会表明该属性属于某个命名空间。
下面的示例包括了这种“有命名空间但没有命名空间前缀”的情况。
js
const element = document.createElement("a");
// set "href" attribute with no namespace and no namespace prefix
element.setAttribute("href", "https://example.com");
// set "href" attribute with namespace and also "xlink" namespace prefix
element.setAttributeNS(
"http://www.w3.org/1999/xlink",
"xlink:href",
"https://example.com",
);
// set "show" attribute with namespace but no namespace prefix
element.setAttributeNS("http://www.w3.org/1999/xlink", "show", "new");
// Iterate over element's attributes
for (const name of element.getAttributeNames()) {
const value = element.getAttribute(name);
console.log(name, value);
}
// logs:
// href https://example.com
// xlink:href https://example.com
// show new
规范
| 规范 |
|---|
| DOM # ref-for-dom-element-getattributenames① |
浏览器兼容性
加载中…