Phần tử DOM HTML thay thếChild()
Ví dụ
Thay thế nút văn bản trong phần tử <li> bằng nút văn bản mới:
const newNode = document.createTextNode("Water");
const element = document.getElementById("myList").children[0];
element.replaceChild(newNode, element.childNodes[0]);
Sự miêu tả
Phương thức replaceChild()
thay thế nút con bằng nút mới.
Xem thêm:
Phương pháp tài liệu liên quan:
Cú pháp
node .replaceChild( newnode , oldnode )
Thông số
Parameter | Description |
newnode | Required. The node to insert. |
oldnode | Required. The node to remove. |
Giá trị trả về
Kiểu | Sự miêu tả |
Nút | Nút được thay thế. |
Thêm ví dụ
Ví dụ
Thay thế phần tử <li> bằng phần tử <li> mới:
// Create a new <li> element:
const element = document.createElement("li");
// Create a new text node:
const textNode = document.createTextNode("Water");
// Append the text node to the <li> element:
element.appendChild(textNode);
// Get the <ul> element with id="myList":
const list = document.getElementById("myList");
// Replace the first child node with the new <li> element:
list.replaceChild(element, list.childNodes[0]);
Trước:
- Coffee
- Tea
- Milk
Sau đó:
- Water
- Tea
- Milk
Hỗ trợ trình duyệt
element.replaceChild()
là tính năng DOM Cấp 1 (1998).
Nó được hỗ trợ đầy đủ trong tất cả các trình duyệt:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | 9-11 |