Phương thức HTML DOM ReplaceChild ()
Thí dụ
Thay thế một nút văn bản trong một phần tử <li> trong danh sách bằng một nút văn bản mới:
// 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"
Trước khi thay thế:
- Coffee
- Tea
- Milk
Sau khi thay thế:
- Water
- Tea
- Milk
Thêm các ví dụ "Hãy tự mình thử" bên dưới.
Định nghĩa và Cách sử dụng
Phương thức ReplaceChild () thay thế một nút con bằng một nút mới.
Nút mới có thể là một nút hiện có trong tài liệu hoặc bạn có thể tạo một nút mới.
Mẹo: Sử dụng phương thức removeChild () để xóa một nút con khỏi một phần tử.
Hỗ trợ trình duyệt
Method | |||||
---|---|---|---|---|---|
replaceChild() | Yes | Yes | Yes | Yes | Yes |
Cú pháp
node.replaceChild(newnode, oldnode)
Giá trị tham số
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 |
Chi tiết kỹ thuật
Giá trị trả lại: | Một đối tượng Node, đại diện cho nút được thay thế |
---|---|
Phiên bản DOM | Đối tượng nút cấp độ lõi 1 |
Các ví dụ khác
Thí dụ
Thay thế một phần tử <li> trong danh sách bằng một phần tử <li> mới:
// 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
Trước khi loại bỏ:
- Coffee
- Tea
- Milk
Sau khi loại bỏ:
- Water
- Tea
- Milk