XML DOMfirstChildプロパティ
❮要素オブジェクト
例
次のコードフラグメントは、「books.xml」をxmlDocにロードし、最初の子ノードを取得します。
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
//
Check if the first node is an element node
function get_firstchild(n) {
var x = n.firstChild;
while (x.nodeType != 1) {
x = x.nextSibling;
}
return x;
}
function myFunction(xml) {
var x, i, txt, firstNode, xmlDoc;
xmlDoc = xml.responseXML;
x = xmlDoc.documentElement;
txt = "";
firstNode = get_firstchild(x);
for (i = 0; i < firstNode.childNodes.length; i++) {
if (firstNode.childNodes[i].nodeType == 1) {
//Process only element nodes
txt += firstNode.childNodes[i].nodeName +
" = " +
firstNode.childNodes[i].childNodes[0].nodeValue + "<br>";
}
}
document.getElementById("demo").innerHTML
= txt;
}
上記のコードの出力は次のようになります。
title = Everyday Italian
author = Giada De Laurentiis
year = 2005
price = 30.00
定義と使用法
firstChildプロパティは、選択した要素の最初の子ノードを返します
選択したノードに子がない場合、このプロパティはNULLを返します。
構文
elementNode.firstChild
ヒントと注意
注: Firefoxおよびその他のほとんどのブラウザーは、空の空白または新しい行をテキストノードとして扱いますが、InternetExplorerは扱いません。したがって、以下の例では、最初の子ノードのノードタイプをチェックする関数があります。
要素ノードのnodeTypeは1であるため、最初の子ノードが要素ノードでない場合は、次のノードに移動し、このノードが要素ノードであるかどうかを確認します。これは、最初の子ノード(要素ノードである必要があります)が見つかるまで続きます。このように、結果はすべてのブラウザで正しくなります。
ヒント:ブラウザー間の違いについて詳しくは、 XMLDOMチュートリアルのDOMブラウザーの章をご覧ください。
❮要素オブジェクト