HTML DOM replaceChild()メソッド
例
リストの<li>要素のテキストノードを新しいテキストノードに置き換えます。
// Create a new text node called "Water"
var textnode = document.createTextNode("Water");
// Get the first child node of an <ul> element
var item = document.getElementById("myList").childNodes[0];
// Replace the first child node of <ul> with the newly created text node
item.replaceChild(textnode, item.childNodes[0]);
// Note: This example replaces only the Text node "Coffee" with a Text node "Water"
交換する前に:
- Coffee
- Tea
- Milk
交換後:
- Water
- Tea
- Milk
以下の「自分で試してみてください」の例をもっと見てください。
定義と使用法
replaceChild()メソッドは、子ノードを新しいノードに置き換えます。
新しいノードは、ドキュメント内の既存のノードである可能性があります。または、新しいノードを作成することもできます。
ヒント:removeChild()メソッドを使用して、要素から子ノードを削除します。
ブラウザのサポート
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
構文
node.replaceChild(newnode, oldnode)
パラメータ値
Parameter | Type | Description |
---|---|---|
newnode | Node object | Required. The node object you want to insert |
oldnode | Node object | Required. The node object you want to remove |
技術的な詳細
戻り値: | 置き換えられたノードを表すNodeオブジェクト |
---|---|
DOMバージョン | コアレベル1ノードオブジェクト |
その他の例
例
リスト内の<li>要素を新しい<li>要素に置き換えます。
// Create a new <li> element
var elmnt = document.createElement("li");
// Create a new text node called "Water"
var textnode = document.createTextNode("Water");
// Append the text node to <li>
elmnt.appendChild(textnode);
// Get the <ul> element with id="myList"
var item = document.getElementById("myList");
// Replace the first child node (<li> with index 0) in <ul> with the newly created <li> element
item.replaceChild(elmnt, item.childNodes[0]);
// Note: This example replaces the entire <li> element
削除する前に:
- Coffee
- Tea
- Milk
削除後:
- Water
- Tea
- Milk