Thuộc tính textContent của XML DOM

Định nghĩa và cách sử dụng

textContent Thiết lập hoặc trả về nội dung văn bản của phần tử và các phần tử con của nó.

Khi đặt, tất cả các phần tử con sẽ bị xóa và thay thế bằng một phần tử văn bản duy nhất chứa giá trị thuộc tính này.

Cú pháp

nodeObject.textContent

Mô hình

Ví dụ 1

Mã dưới đây sẽ tải "books.xml" vào xmlDoc và trả về nội dung văn bản của phần tử <book>:

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.getElementsByTagName('book');
    for(i = 0; i < x.length; i++) {
        txt += x.item(i).textContent + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

Thử ngay

Ví dụ 2

Đặt nội dung văn bản của phần tử:

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.getElementsByTagName('book');
    // Đặt textContent
    for(i = 0; i < x.length; i++) {
        x.item(i).textContent = "Outdated";
    }
    // Xuất textContent
    for(i = 0; i < x.length; i++) {
        txt += x.item(i).textContent + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

Thử ngay