Dom-node-replacechild

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

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

メソッド_replaceChild_は、古い子ノードを新しいノードに置き換えるために使用されます。 これにより、置換されたノードが返されます。

構文

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

nodeObject.replaceChild(Node newChild, Node oldChild)
S.No. Parameter & Description
1

newChild

古い子に置き換えられるのは新しい子です。 タイプは_Node_です。

2

oldChild

このパラメーターは新しい子に置き換えられます。 タイプは_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>

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

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

         x = xmlDoc.documentElement;

         create_e1 = xmlDoc.createElement("Employee");
         create_e2 = xmlDoc.createElement("Email");
         create_t = xmlDoc.createTextNode("[email protected]");

         create_e2.appendChild(create_t);
         create_e1.appendChild(create_e2);

         y = xmlDoc.getElementsByTagName("Employee")[0]
         x.replaceChild(create_e1,y);

         z = xmlDoc.getElementsByTagName("Email")[0];
         document.write("After Replacement  : ")
         document.write(z.childNodes[0].nodeValue);

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

実行

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

After Replacement : [email protected]