Thuộc tính childNodes của XML DOM

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

childNodes Thuộc tính trả về NodeList của các phần tử con của nút cụ thể.

Lưu ý:Bạn có thể sử dụng thuộc tính length để xác định số lượng phần tử con, sau đó lặp qua tất cả các phần tử con và lấy thông tin bạn muốn.

Cú pháp

nodeObject.childNodes

Chi tiết kỹ thuật

Giá trị trả về: Đối tượng NodeList biểu thị tập hợp các nút.
Phiên bản DOM: Core Level 1

Mô hình

Ví dụ 1

Mã dưới đây sẽ tải tệp "books.xml" vào xmlDoc và hiển thị các phần tử con của tài liệu XML:

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, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.childNodes;
    for (i = 0; i < x.length; i++) {
        txt += "Nodename: " + x[i].nodeName +
        " (nodetype: " + x[i].nodeType + ")";
    }
    document.getElementById("demo").innerHTML = txt;
}

Thử trực tiếp

Ví dụ 2

Hiển thị tất cả các phần tử con của tất cả các phần tử trong tài liệu XML:

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, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.documentElement;
    y = x.childNodes;
    for(i = 0; i < y.length; i++) {
        txt += "Nodename: " + y[i].nodeName +
        " (nodetype: " + y[i].nodeType + ")<br>";
        for(z = 0; z < y[i].childNodes.length; z++) {
            txt += "Nodename: " + y[i].childNodes[z].nodeName +
            " (nodetype: " + y[i].childNodes[z].nodeType + ")<br>";
        }
    }
    document.getElementById("demo").innerHTML = 
    "Nodename: " + xmlDoc.nodeName +
    " (nodetype: " + xmlDoc.nodeType + ")<br>"
    "Tennode: " + x.nodeName + "}} 
    " (nodetype: " + x.nodeType + ")<br>" +
    txt;
}

Thử trực tiếp

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ợ childNodes Thuộc tính.