XML DOM setAttributeNode() 方法
❮ 元素对象
示例
下面的代码片段加载 "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);
}
// 输出所有 "edition" 属性值
for (i = 0; i < x.length; i++) {
txt += "Edition: " + x[i].getAttribute("edition") + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
输出
Edition: first
Edition: first
Edition: first
Edition: first
自己动手试一试 »
定义和用法
setAttributeNode() 方法添加一个新的属性节点。
如果元素中已存在同名的属性,则会被新属性替换。如果新属性替换了现有属性,则会返回被替换的属性节点,否则返回 null。
语法
elementNode.setAttributeNode(att_node)
参数 | 描述 |
---|---|
att_node | 必需。指定要设置的属性节点 |
❮ 元素对象