Phương thức XML DOM replaceChild()
定 nghĩa và cách sử dụng
replaceChild()
Phương pháp thay thế một con nút con bằng một con nút con khác.
Khi thành công, hàm này trả về nút đã thay thế, khi thất bại trả về NULL
。
Cú pháp
elementNode.replaceChild(new_node,old_node)
Tham số | Mô tả |
---|---|
new_node | Bắt buộc. Định nghĩa nút mới. |
old_node | Bắt buộc. Định nghĩa con nút cần thay thế. |
Mô hình
Mã dưới đây sẽ 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; // Tạo một phần tử book, phần tử title và một nút văn bản newNode = xmlDoc.createElement("book"); newTitle = xmlDoc.createElement("title"); newText = xmlDoc.createTextNode("Hello World"); // Thêm một nút văn bản vào nút title newTitle.appendChild(newText); // Thêm nút title này vào nút book newNode.appendChild(newTitle); y = xmlDoc.getElementsByTagName("book")[0]; // Sử dụng nút book mới này để thay thế nút book đầu tiên x.replaceChild(newNode, y); z = xmlDoc.getElementsByTagName("title"); // Xuất tất cả title for (i = 0; i < z.length; i++) { txt += z[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; }