XML DOM setAttributeNS()เมธอด
❮ วัตถุธาตุ
ตัวอย่าง
โค้ดย่อยต่อไปนี้โหลด " books_ns.xml " ลงใน xmlDoc และเพิ่มแอตทริบิวต์ "edition" ให้กับองค์ประกอบ <book> แรก:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books_ns.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x =
xmlDoc.getElementsByTagName("book")[0];
var ns =
"https://www.w3schools.com/edition/";
x.setAttributeNS(ns,
"edition", "first");
document.getElementById("demo").innerHTML
=
x.getAttributeNS(ns,"edition");
}
เอาท์พุท:
first
ความหมายและการใช้งาน
เมธอด setAttributeNS() เพิ่มแอตทริบิวต์ใหม่ (พร้อมเนมสเปซ)
หากมีแอตทริบิวต์ที่มีชื่อหรือเนมสเปซนั้นอยู่แล้วในองค์ประกอบ ค่าของแอตทริบิวต์นั้นจะเปลี่ยนเป็นค่าของพารามิเตอร์ส่วนนำหน้าและค่า
ไวยากรณ์
elementNode.setAttributeNS(ns,name,value)
Parameter | Description |
---|---|
ns | Required. Specifies the namespace URI of the attribute to set |
name | Required. Specifies the name of the attribute to set |
value | Required. Specifies the value of the attribute to set |
ตัวอย่าง
โค้ดย่อยต่อไปนี้โหลด " books_ns.xml " เป็น xmlDoc และเปลี่ยนค่า "lang" ขององค์ประกอบ <title> แรก:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "books_ns.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x =
xmlDoc.getElementsByTagName("title")[0];
var ns =
"https://www.w3schools.com/edition/";
x.setAttributeNS(ns,
"c:lang", "italian");
document.getElementById("demo").innerHTML
=
x.getAttributeNS(ns, "lang");
}
เอาท์พุท:
italian
❮ วัตถุธาตุ