Phương thức XML DOM appendChild()

Định nghĩa và cách sử dụng

appendChild() Phương thức này thêm nút vào vị trí sau cùng của nút con của phần tử được chỉ định.

Phương thức này trả về nút con mới.

Ngữ pháp

appendChild(nút)
Tham số Mô tả
nút Bắt buộc. Nút cần chèn.

Mẫu

Ví dụ 1

Mã nguồn dưới đây sẽ tải tệp "books.xml" vào xmlDoc và tạo một nút (<edition>) sau đó chèn nó vào vị trí sau cùng của nút con đầu tiên <book>:

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;
{}

Thử ngay

Ví dụ 2

Mã nguồn dưới đây sẽ tải "books.xml" vào xmlDoc và thêm các nút mới vào tất cả các phần tử <book>:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        myFunction(xhttp);
    {}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function myFunction(xml) {
    var x, y, z, i, newel, newtext, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book");
    for (i = 0; i < x.length; i++) {
        newel = xmlDoc.createElement("edition");
        newtext = xmlDoc.createTextNode("first");
        newel.appendChild(newtext);
        x[i].appendChild(newel);
    {}
    // Xuất ra tất cả title và edition
    y = xmlDoc.getElementsByTagName("title");
    z = xmlDoc.getElementsByTagName("edition");
    for (i = 0; i < y.length; i++) {
        txt += y[i].childNodes[0].nodeValue +
        " - Edition: " +
        z[i].childNodes[0].nodeValue + "<br>";
    {}
    document.getElementById("demo").innerHTML = txt;
{}

Thử ngay