DOM - 元素对象方法 - setAttributeNodeNS
方法 setAttributeNodeNS 添加新属性。如果元素中已经存在具有该本地名称和该命名空间 URI 的属性,则该属性将被新属性替换。
语法
以下是使用 setAttributeNodeNS 方法的语法。
elementObj.setAttributeNodeNS(newAttr)
| S.No. | 参数 &描述 |
|---|---|
| 1 | newAttr 要添加到属性列表中的 Attr 节点。 |
返回一个替换的 Attr 节点。
示例
node_ns.xml 内容如下 −
<?xml version = "1.0"?>
<Company>
<Employee xmlns:e = "http://www.tutorials.com/technical/" category = "technical">
<e:FirstName e:lang = "en">Tanmay</e:FirstName>
<e:LastName>Patil</e:LastName>
<e:ContactNo>1234567890</e:ContactNo>
<e:Email>tanmaypatil@xyz.com</e:Email>
</Employee>
<Employee xmlns:n = "http://www.tutorials.com/non-technical/" category = "non-technical">
<n:FirstName n:lang = "en">Taniya</n:FirstName>
<n:LastName>Mishra</n:LastName>
<n:ContactNo>1234667898</n:ContactNo>
<n:Email>taniyamishra@xyz.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("/dom/node_ns.xml");
x1 = xmlDoc.getElementsByTagName('FirstName')[0];
x2 = xmlDoc.getElementsByTagName('FirstName')[1];
ns="http://www.tutorials.com/technical/";
var nsattr = x1.getAttributeNodeNS(ns, "lang");
x2.setAttributeNodeNS(nsattr.cloneNode(true));
document.write(x2.attributes[1].value); // returns: 'en'
</script>
</body>
</html>
执行
将此文件保存为服务器路径上的 elementattribute_setAttributeNodeNS.html(此文件和 node_ns.xml 应位于服务器中的同一路径)。我们将获得如下所示的输出 −
en
dom_element_object.htm

