Phương pháp XML DOM item()

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

item() Phương pháp này trả về nút tại vị trí chỉ định trong danh sách nút.

Ngữ pháp

item(index)
Tham số Mô tả
index Chỉ số

Mô hình

Ví dụ 1

Mã dưới đây sẽ tải "books.xml" vào xmlDoc, duyệt qua các phần tử <book> và in giá trị thuộc tính category:

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, att, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book');
    for (i = 0; i < x.length; i++) {
        att = x.item(i).attributes.getNamedItem("category");
        txt += att.value + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

Thử nghiệm trực tiếp

Ví dụ 2

Vòng lặp duyệt qua các mục trong danh sách 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.documentElement.childNodes;
    for (i = 0; i < x.length; i++) { 
        if (x.item(i).nodeType == 1) {
            txt += x.item(i).nodeName + "<br>";
        }
    }
    document.getElementById("demo").innerHTML = txt; 
}

Thử nghiệm trực tiếp

Ví dụ 3

Thay đổi giá trị của dự án:

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, attlist, att, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book");
    // Sửa đổi giá trị thuộc tính của thuộc tính category
    for (i = 0; i < x.length; i++) { 
        attlist = x.item(i).attributes;
        att = attlist.getNamedItem("category");
        att.value = "BESTSELLER";
    }
    // Xuất tất cả title và edition
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute("category") + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

Thử nghiệm trực tiếp