NamedNodeMap:setNamedItemNS() 方法

Baseline 已廣泛支援

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

NamedNodeMap 介面的 setNamedItemNS() 方法將地圖中由其名稱標識的 Attr 放入其中。如果地圖中已存在同名 Attr,則會被替換

注意:此方法是 setNamedItem() 的別名,可以互換使用。

語法

js
setNamedItemNS(attr)

引數

attr

要插入到地圖中的屬性。

返回值

如果屬性被替換,則返回舊屬性;如果屬性是新的,則返回 null

異常

InUseAttributeError DOMException

如果屬性仍是另一個地圖的一部分,則丟擲此異常。

示例

html
<span ob:one="one"></span>
<pre></pre>
js
const parser = new DOMParser();
// ob:one in <span> is not in a namespace, while ob:one in <warning>, is.
const xmlString =
  '<warning ob:one="test" xmlns:ob="http://www.example.com/ob">Beware!</warning>';
const doc = parser.parseFromString(xmlString, "application/xml");

const span = document.querySelector("span");
const pre = document.querySelector("pre");
const warning = doc.querySelector("warning");
const attrMap = span.attributes;

let result = `The '<span>' element initially contains ${attrMap.length} attribute.\n\n`;

result += "We remove `one` from '<span>' and adds it to '<pre>'.\n";
const one = warning.attributes.removeNamedItemNS(
  "http://www.example.com/ob",
  "one",
);
attrMap.setNamedItemNS(one);
result += `The '<span>' element now contains ${span.attributes.length} attributes:\n\n`;
result += "Prefix\tLocal name\tQualified name\n";
result += "=========================================\n";

for (const attr of attrMap) {
  result += `${attr.prefix}\t${attr.localName}\t\t${attr.name}\n`;
}

pre.textContent = result;

規範

規範
DOM
# dom-namednodemap-setnameditemns

瀏覽器相容性