DOM Node對象insertBefore()方法

DOM Node對象insertBefore()方法將新節點作為此節點的子節點插入,直接在此節點的現有子節點之前的位置插入。 它返回當前要插入的節點。

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

nodeObject.insertBefore(Node newChild, Node refChild)

參數

  • newChild - 它是要添加的新節點,它是Node類型。
  • refChild - 它用作參考節點,在此之前添加新節點,它是Node類型。

返回值

  • 此方法返回正在插入的節點。

示例

檔: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>

以下示例演示了insertBefore方法的用法,檔:insertbefore.html -

<!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");

         create_e = xmlDoc.createElement("Email");

         f1 = xmlDoc.documentElement;
         f2 = xmlDoc.getElementsByTagName("Email");

         document.write("插入操作之前沒有Email元素: " + f2.length);
         document.write(" <br>");
         f1.insertBefore(create_e,f2[3]);

         f2 = xmlDoc.getElementsByTagName("Email");
         document.write("插入操作之後沒有Email元素: " + f2.length);
      </script>
   </body>
</html>

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


上一篇: DOM Node對象 下一篇: DOM NodeList對象