XML DOM setAttributeNS() 方法
定義和用法
setAttributeNS()
方法添加新屬性(帶有命名空間)。
如果元素中已存在擁有該名稱或命名空間的屬性,則其值將更改為 value 參數。
語法
elementNode.setAttributeNS(ns,name,value)
參數 | 描述 |
---|---|
ns | 必需。規定要設置的屬性的命名空間 URI。 |
name | 必需。規定要設置的屬性的名稱。 |
value | 必需。規定要設置的屬性的值。 |
實例
例子 1
下面的代碼將 "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://www.codew3c.com/edition/"; x.setAttributeNS(ns, "edition", "first"); document.getElementById("demo").innerHTML = x.getAttributeNS(ns,"edition"); }
例子 2
下面的代碼將 "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://www.codew3c.com/edition/"; x.setAttributeNS(ns, "c:lang", "italian"); document.getElementById("demo").innerHTML = x.getAttributeNS(ns, "lang"); }