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 += "Nodename: " + x[i].nodeName + " (nodetype: " + 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 += "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>" + "Nodename: " + x.nodeName + " (nodetype: " + x.nodeType + ")<br>" + txt; }
瀏覽器支持
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
支持 | 支持 | 支持 | 支持 | 支持 |
所有主流瀏覽器都支持 childNodes
屬性。