XML DOM setAttributeNode() メソッド
定義と使用方法
setAttributeNode()
新しい属性ノードを追加する方法。
要素に同名の属性が存在する場合、それを新しい属性に置き換えます。
新しい属性が既存の属性を置き換えた場合、置き換えられた属性ノードを返します。そうでない場合は null を返します。
文法
elementNode.setAttributeNode(att_node)
パラメータ | 説明 |
---|---|
att_node | 必須。設定する属性ノードを指定します。 |
例
以下のコードは「books.xml」を xmlDoc にロードし、すべての <book> 要素に「edition」属性を追加します:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { myFunction(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function myFunction(xml) { var x, y, z, i, newatt, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName('book'); for (i = 0; i < x.length; i++) { newatt = xmlDoc.createAttribute("edition"); newatt.value = "first"; x[i].setAttributeNode(newatt); } // 全ての「版」属性値を出力します。全ての「版」属性値を出力します for (i = 0; i < x.length; i++) { txt += "Edition: " + x[i].getAttribute("edition") + "<br>"; } document.getElementById("demo").innerHTML = txt; }