Phương thức XML DOM ReplaceChild ()
❮ Đối tượng nút
Thí dụ
Đoạn mã sau tải " books.xml " vào xmlDoc và thay thế phần tử <book> đầu tiên:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
var x, y, z, i, newNode, newTitle, newText,
xmlDoc, txt;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.documentElement;
// Create a book
element, title element and a text node
newNode = xmlDoc.createElement("book");
newTitle = xmlDoc.createElement("title");
newText = xmlDoc.createTextNode("A
Notebook");
// Add a text node to the title node
newTitle.appendChild(newText);
// Add the title node to the book node
newNode.appendChild(newTitle);
y = xmlDoc.getElementsByTagName("book")[0];
// Replace the first book node with the new book node
x.replaceChild(newNode,
y);
z = xmlDoc.getElementsByTagName("title");
// Output all titles
for (i = 0; i < z.length; i++) {
txt += z[i].childNodes[0].nodeValue
+ "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
Đầu ra của đoạn mã trên sẽ là:
A Notebook
Harry Potter
XQuery Kick Start
Learning XML
Đị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: Nút con được thay thế có thể được chèn sau này vào bất kỳ phần tử nào trong cùng một tài liệu. Sử dụng phương thức insertBefore () hoặc appendChild () để chèn sau này vào cùng một tài liệu, hoặc sử dụng phương thức acceptNode () hoặc importNode () để chèn nút được thay thế vào tài liệu khác.
Hỗ trợ trình duyệt
Phương thức ReplaceChild () được hỗ trợ trong tất cả các trình duyệt chính.
Cú pháp
nodeObject.replaceChild(newchild,oldchild)
Thông số
Parameter | Type | Description |
---|---|---|
newchild | Node object | Required. The new node to put in the child list |
oldchild | Node object | Required. The node that will be replaced in the child list |
Giá trị trả lại
Type | Description |
---|---|
Node object | The replaced node (oldchild) |
Chi tiết kỹ thuật
Phiên bản DOM | Đối tượng nút cấp độ lõi 1. Đã sửa đổi trong DOM cấp 3 |
---|
❮ Đối tượng nút