Dom-node-insertbefore

提供:Dev Guides
移動先:案内検索

DOM-ノードオブジェクトメソッド-insertBefore

メソッド_insertBefore_は、このノードの既存の子の直前に、このノードの子として新しいノードを挿入します。 挿入されるノードを返します。

構文

_insertBefore_メソッドを使用するための構文は次のとおりです。

nodeObject.insertBefore(Node newChild, Node refChild)
S.No. Parameter & Description
1

newChild

追加される新しいノードです。 タイプは_Node_です。

2

refChild

これは、新しいノードが追加される前の参照ノードとして使用されます。 タイプは_Node_です。

このメソッドは、挿入されているノードを返します。

_node.xml_の内容は以下のとおりです-

<?xml version = "1.0"?>
<Company>
   <Employee category = "Technical">
      <FirstName>Tanmay</FirstName>
      <LastName>Patil</LastName>
      <ContactNo>1234567890</ContactNo>
      <Email>[email protected]</Email>
   </Employee>

   <Employee category = "Non-Technical">
      <FirstName>Taniya</FirstName>
      <LastName>Mishra</LastName>
      <ContactNo>1234667898</ContactNo>
      <Email>[email protected]</Email>
   </Employee>

   <Employee category = "Management">
      <FirstName>Tanisha</FirstName>
      <LastName>Sharma</LastName>
      <ContactNo>1234562350</ContactNo>
      <Email>[email protected]</Email>
   </Employee>
</Company>

次の例は、_insertBefore_メソッドの使用方法を示しています-

<!DOCTYPE html>
<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.xml");

         create_e = xmlDoc.createElement("Email");

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

         document.write("No of Email elements before insert operation: " + f2.length);
         document.write(" <br>");
         f1.insertBefore(create_e,f2[3]);

         f2 = xmlDoc.getElementsByTagName("Email");
         document.write("No of Email elements after insert operation: " + f2.length);
      </script>
   </body>
</html>

実行

このファイルを_nodemethod_insertbefore_としてサーバーパスに保存します(このファイルとnode.xmlはサーバーの同じパスにある必要があります)。 次のように出力を取得します-

No of Email elements before insert operation: 3
No of Email elements after insert operation: 4