DOM - 元素对象方法 - setAttributeNS

方法 setAttributeNS 添加新属性。如果元素上已经存在具有相同本地名称和命名空间 URI 的属性,则其前缀将更改为qualifiedName 的前缀部分,其值将更改为值参数。

语法

以下是使用 setAttributeNS 方法的语法。

elementObj.setAttributeNS(namespace,name,value)

S.No. 参数 &描述
1

namespace

它是一个指定属性命名空间的字符串。

2

name

它是一个标识要设置的属性的字符串。

3

value

它是新属性的所需字符串值属性。

示例

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>

以下示例演示了 setAttributeNS 方法的用法 −

<!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");
         x = xmlDoc.getElementsByTagName('FirstName')[0];
         ns="http://www.tutorials.com/technical/";
         document.write("<b>Before using setattributeNS method: </b> ");
         document.write(x.getAttributeNS(ns,"lang"));
         x.setAttributeNS(ns,"lang","DE");
         document.write("<br><b>After using setattributeNS method: </b> ");
         document.write(x.getAttributeNS(ns,"lang"));
      </script>
   </body>
</html>

执行

将此文件保存为服务器路径上的 elementattribute_setAttributeNS.html(此文件和 node_ns.xml 应位于服务器中的同一路径)。我们将获得如下所示的输出 −

Before using setattributeNS method: en
After using setattributeNS method: DE
dom_element_object.htm