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.w3schools.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.w3schools.com/edition/"; x.setAttributeNS(ns, "c:lang", "italian"); document.getElementById("demo").innerHTML = x.getAttributeNS(ns, "lang"); }