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① |
瀏覽器相容性
載入中…