DOM Element对象setAttributeNodeNS()
方法添加了一个新属性。 如果元素中已存在具有该本地名称和该命名空间URI的属性,则该属性将替换为新属性。
语法
以下是setAttributeNodeNS()
方法的使用语法。
elementObj.setAttributeNodeNS(newAttr)
参数
newAttr
- 要添加到属性列表的Attr
节点。
返回值
- 它返回一个替换的
Attr
节点。
示例
文件:node_ns.xml 的内容如下 -
<?xml version = "1.0"?>
<Company>
<Employee xmlns:e = "http://www.yiibai.com/technical/" category = "technical">
<e:FirstName e:lang = "en">Maary</e:FirstName>
<e:LastName>Su</e:LastName>
<e:ContactNo>1234567890</e:ContactNo>
<e:Email>tanmay@yiibai.com</e:Email>
</Employee>
<Employee xmlns:n = "http://www.yiibai.com/non-technical/" category = "non-technical">
<n:FirstName n:lang = "en">Tianya</n:FirstName>
<n:LastName>Lee</n:LastName>
<n:ContactNo>1234667898</n:ContactNo>
<n:Email>tianya@yiibai.com</n:Email>
</Employee>
</Company>
以下示例演示了setAttributeNodeNS()
方法的用法 -
<!DOCTYPE html>
<head>
<script>
function loadXMLDoc(filename) {
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else // code for IE5 and IE6
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
</script>
</head>
<body>
<script>
xmlDoc = loadXMLDoc("/node_ns.xml");
x1 = xmlDoc.getElementsByTagName('FirstName')[0];
x2 = xmlDoc.getElementsByTagName('FirstName')[1];
ns="http://www.yiibai.com/technical/";
var nsattr = x1.getAttributeNodeNS(ns, "lang");
x2.setAttributeNodeNS(nsattr.cloneNode(true));
document.write(x2.attributes[1].value); // returns: 'en'
</script>
</body>
</html>
执行上面示例代码,得到以下结果 -
en