NamedNodeMap: Methode setNamedItem()

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 Map ein. Wenn bereits ein Attr mit demselben Namen in der Map vorhanden ist, wird es ersetzt.

Syntax

js
setNamedItem(attr)

Parameter

attr

das Attribut, das in die Map 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 Map ist.

Beispiel

html
<span one="one" two="two"></span>
<pre test="testValue"></pre>
js
const span = document.querySelector("span");
const pre = document.querySelector("pre");
const attrMap = pre.attributes;

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

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

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

pre.textContent = result;

Spezifikationen

Specification
DOM
# dom-namednodemap-setnameditem

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
setNamedItem

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support