XML DOM replaceData() 方法

定義和用法

replaceData() 方法替換注釋節點中的數據。

語法

commentNode.replaceData(start,length,string)
參數 描述
start 必需。規定從何處開始替換字符。起始值從零開始。
length 必需。規定要替換的字符數。
string 必需。規定要插入的字符串。

實例

下面的代碼將 "books_comment.xml" 加載到 xmlDoc 中,并在第一個 <book> 元素的注釋節點中將 "Simple" 替換為 "Easy":

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, txt, xmlDoc;
    xmlDoc = xml.responseXML;
   txt = "";
    x = xmlDoc.getElementsByTagName("book")[0].childNodes;
    for (i = 0; i < x.length; i++) {
    // Process only comment nodes
        if (x[i].nodeType == 8) {
            x[i].replaceData(4, 6, "Easy");
            txt += x[i].data + "<br>";
        }
    }
    document.getElementById("demo").innerHTML = txt;
}

親自試一試

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