Element: setAttributeNodeNS() メソッド

setAttributeNodeNS は、名前空間付きの新しい属性ノードを要素へ追加します。

構文

js
setAttributeNodeNS(attributeNode)

引数

  • attributeNodeAttr ノードです。

返値

置換された属性ノードが、もしあれば、この関数から返されます。

js
// <div id="one" xmlns:myNS="http://www.mozilla.org/ns/specialspace"
//            myNS:special-align="utterleft">one</div>
// <div id="two">two</div>

const myns = "http://www.mozilla.org/ns/specialspace";
const d1 = document.getElementById("one");
const d2 = document.getElementById("two");
const a = d1.getAttributeNodeNS(myns, "special-align");
d2.setAttributeNodeNS(a.cloneNode(true));
alert(d2.attributes[1].value); // 返値: `utterleft'

メモ

指定された属性が既に要素に存在する場合、その属性は新しい属性に置き換えられ、置き換えられた属性が返されます。

なお、ノードを複製せずに設定しようとすると、Mozilla は NS_ERROR_DOM_INUSE_ATTRIBUTE_ERR "Attribute already in use" エラーを出します。DOM は Attr を再利用するにあたって複製することを要求しているからです(他のノードが移動できるのとは異なります)。

DOM メソッドは要素の属性を取り扱います。

名前空間に無関係、
最も一般的に使用されるメソッド
名前空間に限定される変数
(DOM Level 2)
Attr ノードを直接扱う DOM レベル 1 のメソッド
(ほとんど使用されない)
Attr ノードを直接扱う DOM レベル 2 名前空間に限定されるメソッド
(ほとんど使用されない)
setAttribute (DOM 1) setAttributeNS setAttributeNode setAttributeNodeNS
getAttribute (DOM 1) getAttributeNS getAttributeNode getAttributeNodeNS
hasAttribute (DOM 2) hasAttributeNS - -
removeAttribute (DOM 1) removeAttributeNS removeAttributeNode -

仕様書

Specification
DOM Standard
# dom-element-setattributenodens

ブラウザーの互換性

BCD tables only load in the browser

関連情報