Để thay thế child node bằng node mới, JavaScript cung cấp replaceChild(). Tạo node mới trước, sau đó dùng replaceChild() thay node cũ.
Cú pháp
parentNode.replaceChild(newNode, oldNode);
Ví dụ
List ban đầu: Boost, Horlicks, Maltova. Thay element đầu bằng Bournavita.
<html> <body> <ul id="List"><li>Boost</li><li>Horlicks</li><li>Maltova</li></ul> <script> var newnode = document.createTextNode("Bournavita"); var item = document.getElementById("List").childNodes[0]; item.replaceChild(newnode, item.childNodes[0]); </script> </body> </html>
Kết quả
Bournavita Horlicks Maltova
Lưu ý: Ví dụ gốc có lỗi: item là text node (childNodes[0] của ul), text node không có replaceChild. Cách đúng:
var list = document.getElementById('List');
var oldLi = list.children[0]; // hoặc list.querySelector('li')
var newLi = document.createElement('li');
newLi.textContent = 'Bournavita';
list.replaceChild(newLi, oldLi);
Hoặc thay text content trực tiếp: oldLi.textContent = 'Bournavita'.