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);
}
// 输出所有“版本”属性值Output all "edition" attribute values
for (i = 0; i < x.length; i++) {
txt += "Edition: " + x[i].getAttribute("edition") + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}