XML DOM setAttributeNS() 方法
❮ 元素物件
示例
下面的程式碼片段將 "books_ns.xml" 載入到 xmlDoc 中,併為第一個 <book> 元素新增一個 "edition" 屬性
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://w3schools.tw/edition/";
x.setAttributeNS(ns, "edition", "first");
document.getElementById("demo").innerHTML =
x.getAttributeNS(ns,"edition");
}
輸出
first
自己動手試一試 »
定義和用法
setAttributeNS() 方法新增一個新屬性(帶名稱空間)。
如果元素中已存在同名或同命名空間的屬性,則其值將被 prefix 和 value 引數的值覆蓋。
語法
elementNode.setAttributeNS(ns,name,value)
引數 | 描述 |
---|---|
ns | 必需。指定要設定的屬性的名稱空間 URI |
name | 必需。指定要設定的屬性的名稱 |
value | 必需。指定要設定的屬性的值 |
示例
下面的程式碼片段將 "books_ns.xml" 載入到 xmlDoc 中,並更改第一個 <title> 元素的 "lang" 值
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://w3schools.tw/edition/";
x.setAttributeNS(ns, "c:lang", "italian");
document.getElementById("demo").innerHTML =
x.getAttributeNS(ns, "lang");
}
輸出
italian
自己動手試一試 »
❮ 元素物件