XML DOM childNodes 属性

定義と使用方法

childNodes 指定されたノードの子ノードを NodeList で返します。

ヒント:length 属性を使用して子ノードの数を決定し、すべての子ノードをループして必要な情報を抽出することができます。

文法

nodeObject.childNodes

技術的詳細

返り値: ノード集合を表す NodeList オブジェクト。
DOM バージョン: Core Level 1

例 1

以下のコードは "books.xml" を xmlDoc に読み込み、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 += "ノード名: " + x[i].nodeName +
        "(ノードタイプ: " + x[i].nodeType + ")"
    }
    document.getElementById("demo").innerHTML = txt;
}

実際に試してみてください

例 2

表示 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 += "ノード名: " + y[i].nodeName +
        "(ノードタイプ: " + y[i].nodeType + ")<br>"
        for(z = 0; z < y[i].childNodes.length; z++) {
            txt += "ノード名: " + y[i].childNodes[z].nodeName +
            "(ノードタイプ: " + y[i].childNodes[z].nodeType + ")<br>"
        }
    }
    document.getElementById("demo").innerHTML = 
    "ノード名: " + xmlDoc.nodeName +
    "(ノードタイプ: " + xmlDoc.nodeType + ")<br>"
    "Nodename: " + x.nodeName +"}} 
    " (nodetype: " + x.nodeType + ")<br>" +
    txt;
}

実際に試してみてください

ブラウザサポート

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
サポート サポート サポート サポート サポート

すべての主要ブラウザがサポートしています childNodes 属性。