HTML DOM replaceChild() Metode
Contoh
Ganti simpul teks dalam elemen <li> dalam daftar dengan simpul teks baru:
// 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"
Sebelum mengganti:
- Coffee
- Tea
- Milk
Setelah mengganti:
- Water
- Tea
- Milk
Lebih banyak contoh "Coba Sendiri" di bawah ini.
Definisi dan Penggunaan
Metode replaceChild() menggantikan simpul anak dengan simpul baru.
Node baru dapat berupa node yang sudah ada dalam dokumen, atau Anda dapat membuat node baru.
Tip: Gunakan metode removeChild() untuk menghapus simpul anak dari sebuah elemen.
Dukungan Peramban
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
Sintaksis
node.replaceChild(newnode, oldnode)
Nilai Parameter
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 |
Detail Teknis
Nilai Kembali: | Objek Node, mewakili node yang diganti |
---|---|
Versi DOM | Objek Node Tingkat 1 Inti |
Lebih Banyak Contoh
Contoh
Ganti elemen <li> dalam daftar dengan elemen <li> baru:
// 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
Sebelum menghapus:
- Coffee
- Tea
- Milk
Setelah menghapus:
- Water
- Tea
- Milk