Método item() do DOM XML

Definição e uso

item() O método item() retorna o nó na lista de nós DOM especificado pelo índice.

Sintaxe

item(index)
Parâmetro Descrição
index Índice

Exemplo

Exemplo 1

O código a seguir carrega "books.xml" para xmlDoc, percorre o elemento <book> e imprime o valor do atributo category:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       minhaFuncao(this);
   }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function minhaFuncao(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;
}

Experimente pessoalmente

Exemplo 2

Percore a lista de nós:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        minhaFuncao(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function minhaFuncao(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; 
}

Experimente pessoalmente

Exemplo 3

Alterar o valor do projeto:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        minhaFuncao(this);
    }
};
xhttp.open("GET", "books.xml", true);
xhttp.send();
function minhaFuncao(xml) {
    var x, i, attlist, att, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName("book");
    // Modificar o valor do atributo category
    for (i = 0; i < x.length; i++) { 
        attlist = x.item(i).attributes;
        att = attlist.getNamedItem("category");
        att.value = "MELHOR VENDIDO";
    }
    // Imprimir todos os title e edition
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute("category") + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

Experimente pessoalmente