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

浏览器兼容性