このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

NamedNodeMap.setNamedItem()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2015年7月⁩.

setNamedItem()NamedNodeMap インターフェイスのメソッドで、名前によって識別される属性 (Attr) をこのマップに設定します。 すでに同じ名前の Attr がこのマップに存在した場合は、置き換えます

構文

js
setNamedItem(attr);

引数

attr

このマップに挿入する属性です。

返値

置き換えた場合は古い属性を返します。属性が新規の場合は null です。

例外

InUseAttributeError DOMException

この属性が他のマップに所属していた場合に発生します。

html
<span one="one" two="two"></span>
<pre test="testValue"></pre>
js
const span = document.getElementsByTagName("span")[0];
const pre = document.getElementsByTagName("pre")[0];
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 (e) {
  result += `An exception has been raised: ${e.name}.\n`;
}

pre.textContent = result;

仕様書

Specification
DOM
# dom-namednodemap-setnameditem

ブラウザーの互換性