metoda getNamedItem() DOM XML

definicja i użycie

getNamedItem() metoda zwraca węzeł o określonej nazwie (z namedNodeMap).

język

namedNodeMap.getNamedItem(nodeName)

Parametry

Parametry Opis
nodeName Wymagane. String. Nazwa węzła do zwrócenia.

Szczegóły techniczne

Wersja DOM: Core Level 1
Zwrócona wartość:

Obiekt Node. Posiada węzeł o określonej nazwie.

Jeśli żaden węzeł w mapie nie jest oznaczony, zwróć null.

Przykład

Poniższy kod ładuje "books.xml" do xmlDoc, przechodzi przez elementy <book> i wyświetla wartości atrybutu "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;
}

Spróbuj sam

Przykład 2

Zmień wartość atrybutu:

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");
    // Zmień wartość atrybutu "category"
    for (i = 0; i < x.length; i++) { 
        attlist = x.item(i).attributes;
        att = attlist.getNamedItem("category");
        att.value = "BESTSELLER";
    }
    // Wyświetl wszystkie tytuły i wydania
    for (i = 0; i < x.length; i++) { 
        txt += x[i].getAttribute("category") + "<br>";
    }
    document.getElementById("demo").innerHTML = txt; 
}

Spróbuj sam

Wspierane przeglądarki

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
Wspierane Wspierane Wspierane Wspierane Wspierane

Wszystkie popularne przeglądarki wspierają to. getNamedItem() Metoda.

Komentarz:Internet Explorer 8 i wcześniejsze wersje nie obsługuje tej metody.