Phương thức appendChild() của XML DOM
Định nghĩa và cách sử dụng
appendChild()
Phương thức này sẽ chèn một nút con mới vào cuối danh sách các nút con của đối tượng.
Lưu ý:Nếu newchild Nếu nó đã có trong cây, hãy xóa nó trước.
Cú pháp
nodeObject.appendChild(newchild)
Tham số | Mô tả |
---|---|
newchild | Nút cần thêm. |
Chi tiết kỹ thuật
Phiên bản DOM: | Đối tượng Node Cấp Cơ bản 1. Được sửa đổi trong DOM Level 3. |
---|---|
Giá trị trả về: | Đối tượng Node. Nút được chèn. |
Mô hình
Ví dụ 1
Mã nguồn dưới đây sẽ tải "books.xml" vào xmlDoc và tạo một nút (<edition>) để chèn vào sau nút con cuối cùng của 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 xmlDoc = xml.responseXML; var newel = xmlDoc.createElement("edition"); var x = xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newel); document.getElementById("demo").innerHTML = x.getElementsByTagName("edition")[0].nodeName; }
Example 2
Append child nodes to all <book> nodes:
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, xLen, yLen, newEle, newText, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("book"); xLen = x.length; for (i = 0; i < xLen; i++) { newEle = xmlDoc.createElement("edition"); newText = xmlDoc.createTextNode("first"); newEle.appendChild(newText); x[i].appendChild(newEle); } // Output all title and edition y = xmlDoc.getElementsByTagName("title"); yLen = y.length z = xmlDoc.getElementsByTagName("edition"); for (i = 0; i < yLen; i++) { txt += y[i].childNodes[0].nodeValue + " - Edition: " + z[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; }
Hỗ trợ trình duyệt
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Hỗ trợ | Hỗ trợ | Hỗ trợ | Hỗ trợ | Hỗ trợ |
Tất cả các trình duyệt phổ biến đều hỗ trợ phương thức appendChild()