DOM NamedNodeMap對象setNamedItem()方法

DOM NamedNodeMap對象setNamedItem()方法使用nodeName屬性添加節點。 如果此映射中已存在具有該名稱的節點,則該節點將替換為新映射。

語法

以下是setNamedItem()方法的使用語法。

nodemapObject.setNamedItem(arg)

參數

  • arg - 這將節點存儲在映射中,之後可以使用nodeName屬性訪問此節點值。 它是類型節點。

返回值

  • 如果替換現有節點,則此方法返回節點的新更新值,否則返回null

示例

檔:node.xml 的內容如下 -

<Company>
   <Employee category = "Technical" id = "firstelement">
      <FirstName>Susen</FirstName>
      <LastName>Su</LastName>
      <ContactNo>1584567890</ContactNo>
      <Email>susen@xuhuhu.com</Email>
   </Employee>

   <Employee category = "Non-Technical">
      <FirstName>Max</FirstName>
      <LastName>Su</LastName>
      <ContactNo>1334667898</ContactNo>
      <Email>maxsu@xuhuhu.com</Email>
   </Employee>

   <Employee category = "Management">
      <FirstName>Min</FirstName>
      <LastName>Su</LastName>
      <ContactNo>1364562350</ContactNo>
      <Email>minsu@xuhuhu.com</Email>
   </Employee>
</Company>

以下示例演示了setNamedItem()方法的用法 -

<!DOCTYPE html>
<html>
   <meta charset="utf-8"/>
    <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.xml");

         c = xmlDoc.createAttribute("category");
         c.value = "zaixian zaixian";
         y = xmlDoc.getElementsByTagName('Employee')[0].attributes;
         y.setNamedItem(c);
         document.write("設置名為Item的值為 : ")
         document.write(y.getNamedItem('category').nodeValue);

      </script>
    </body>
</html>

執行上面代碼,得到以下結果 -


上一篇: DOM NamedNodeMap對象 下一篇: DOMImplementation對象