HTML DOM แทนที่Child() Method
ตัวอย่าง
แทนที่โหนดข้อความในองค์ประกอบ <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
ตัวอย่าง "ลองใช้เอง" เพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
เปลี่ยนโหนด () วิธีการแทนที่โหนดย่อยด้วยโหนดใหม่
โหนดใหม่อาจเป็นโหนดที่มีอยู่ในเอกสาร หรือคุณสามารถสร้างโหนดใหม่ได้
เคล็ดลับ:ใช้ เมธอด 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 |
รายละเอียดทางเทคนิค
คืนมูลค่า: | โหนดอ็อบเจ็กต์ แทนโหนดที่ถูกแทนที่ |
---|---|
เวอร์ชัน 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