XML DOM setAttribute() 方法

定义和用法

setAttribute() 方法添加新属性。

如果元素中已存在同名的属性,则将其值更改为 value 参数的值。

语法

elementNode.setAttribute(name,value)
参数 描述
name 必需。规定要设置的属性的名称。
value 必需。规定要设置的属性的值。

实例

例子 1

下面的代码将 "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, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('title');
    // 向每个 title 元素添加一个新属性
    for (i = 0; i < x.length; i++) {
        x[i].setAttribute("edition", "first");
    }
    // 输出 title 和 edition 值
    for (i = 0; i < x.length; i++) {
        txt += x[i].childNodes[0].nodeValue +
        " - Edition: " +
        x[i].getAttribute('edition') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

亲自试一试

例子 2

通过 setAttribute() 更改属性的值:

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, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book');
    for (i = 0; i < x.length; i++) { 
        x.item(i).setAttribute("category", "BESTSELLER");  
    }
    // 输出所有属性值
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute('category') + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

亲自试一试