XML DOM setAttribute()เมธอด
❮ วัตถุธาตุ
ตัวอย่าง
โค้ดย่อยต่อไปนี้โหลด " books.xml " ลงใน xmlDoc และเพิ่มแอตทริบิวต์ "edition" ให้กับองค์ประกอบ <book> ทั้งหมด:
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');
// Add a new
attribute to each title element
for (i = 0; i <
x.length; i++) {
x[i].setAttribute("edition",
"first");
}
// Output titles
and edition value
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue +
" - Edition: " +
x[i].getAttribute('edition')
+ "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
เอาท์พุท:
Everyday Italian - Edition: first
Harry Potter - Edition: first
XQuery Kick Start - Edition: first
Learning XML - Edition: first
ความหมายและการใช้งาน
setAttribute() วิธีการเพิ่มแอตทริบิวต์ใหม่
หากมีแอตทริบิวต์ที่มีชื่อนั้นอยู่แล้วในองค์ประกอบ ค่าของแอตทริบิวต์นั้นจะเปลี่ยนเป็นค่าของค่าพารามิเตอร์
ไวยากรณ์
elementNode.setAttribute(name,value)
Parameter | Description |
---|---|
name | Required. Specifies the name of the attribute to set |
value | Required. Specifies the value of the attribute to set |
ทดลองด้วยตัวเอง
❮ วัตถุธาตุ