NamedNodeMap: setNamedItem()-Methode

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Die setNamedItem()-Methode der NamedNodeMap-Schnittstelle fügt das durch seinen Namen identifizierte Attr in die Liste ein. Wenn bereits ein Attr mit demselben Namen in der Liste vorhanden ist, wird es ersetzt.

Syntax

js
setNamedItem(attr)

Parameter

attr

das Attribut, das in die Liste eingefügt werden soll.

Rückgabewert

Gibt das alte Attribut zurück, wenn es ersetzt wurde, oder null, wenn das Attribut neu ist.

Ausnahmen

InUseAttributeError DOMException

Wird ausgelöst, wenn das Attribut noch Teil einer anderen Liste ist.

Beispiel

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;

Spezifikationen

Specification
DOM
# dom-namednodemap-setnameditem

Browser-Kompatibilität