مетод XML DOM appendChild()

تعریف و استفاده

appendChild() این روش گره‌ای را در آخرین فرزند یک گره مشخص اضافه می‌کند.

این روش یک فرزند جدید را بازمی‌گرداند.

نحوه‌ی استفاده

appendChild(گره)
پارامتر توضیح
گره ضروری. گره‌ای که باید اضافه شود.

مثال

مثال 1

کد زیر "books.xml" را به xmlDoc بارگذاری می‌کند، یک گره (<edition>) ایجاد می‌کند و آن را به آخرین فرزند اولین گره <book> اضافه می‌کند:

متغیر var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   اگر (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   {}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
دستور کار function myFunction(xml) {
    متغیر xmlDoc = xml.responseXML;
    متغیر newel = xmlDoc.createElement("edition");
    متغیر x = xmlDoc.getElementsByTagName("book")[0];
    x.appendChild(newel);
    document.getElementById("demo").innerHTML =
    x.getElementsByTagName("edition")[0].nodeName;
{}

亲自试一试

مثال 2

این کد "books.xml" را به xmlDoc بارگذاری می‌کند و گره‌های جدید را به همه عناصر <book> اضافه می‌کند:

متغیر var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    اگر (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");
    برای (i = 0; i < x.length; i++) {
        newel = xmlDoc.createElement("edition");
        newtext = xmlDoc.createTextNode("first");
        newel.appendChild(newtext);
        x[i].appendChild(newel);
    {}
    // همه title و edition را چاپ کن
    y = xmlDoc.getElementsByTagName("title");
    z = xmlDoc.getElementsByTagName("edition");
    برای (i = 0; i < y.length; i++) {
        txt += y[i].childNodes[0].nodeValue +""
        " - Edition: " +
        z[i].childNodes[0].nodeValue + "<br>";
    {}
    document.getElementById("demo").innerHTML = txt;
{}

亲自试一试