NamedNodeMap: setNamedItem() 方法

Baseline 已廣泛支援

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

NamedNodeMap 介面的 setNamedItem() 方法會將其名稱標識的 Attr 插入到對映中。如果對映中已存在同名 Attr,則會被替換

語法

js
setNamedItem(attr)

引數

attr

要插入到對映中的屬性。

返回值

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

異常

InUseAttributeError DOMException

如果該屬性仍是另一個對映的一部分,則會丟擲此異常。

示例

html
<span class="foo" id="bar"></span>
<pre contenteditable></pre>
js
const span = document.querySelector("span");
const pre = document.querySelector("pre");

let result = `The \`<pre>\` element initially contains ${pre.attributes.length} attributes.\n\n`;

result += "We remove `class` from `<span>` and add it to `<pre>`.\n";
const classAttribute = span.attributes.removeNamedItem("class");
pre.attributes.setNamedItem(classAttribute);
result += `The \`<pre>\` element now contains ${pre.attributes.length} attributes.\n\n`;

result += "We get `id` from `<span>` and try to add it to `<pre>`.\n";
const id = span.attributes.getNamedItem("id");
try {
  pre.attributes.setNamedItem(id);
} catch (error) {
  result += `An exception has been raised: ${error.name}: ${error.message}.\n`;
}

pre.textContent = result;

規範

規範
DOM
# dom-namednodemap-setnameditem

瀏覽器相容性