XML DOM length 屬性

定義和用法

length 屬性返回注釋節點中文本的長度(以字符計)。

語法

commentNode.length

實例

下面的代碼將 "books_comment.xml" 加載到 xmlDoc 中,并從第一個 <title> 元素中獲取文本節點數據和長度:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books_comment.xml", true);
xhttp.send();
function myFunction(xml) {
    var x, i, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book")[0].childNodes;
    for (i = 0; i < x.length; i++) {
    // 只處理注釋節點
        if (x[i].nodeType == 8) {
            txt += x[i].length + "<br>";
        }
    }
    document.getElementById("demo").innerHTML = txt;
}

親自試一試

在上面的例子中,我們用了循環和 if 測試語句,來確保我們只處理注釋節點。注釋節點的節點類型為 8。