Metoda XML DOM setAttributeNode()

Definicja i użycie

setAttributeNode() Metoda dodaje nowy węzeł atrybutu.

Jeśli element zawiera już atrybut o tej samej nazwie, zastępuje go nowym atrybutem.

Jeśli nowy atrybut zastępuje istniejący atrybut, zwraca zastąpiony węzeł atrybutu, w przeciwnym razie zwraca null.

Gramatyka

elementNode.setAttributeNode(att_node)
Parametry Opis
att_node Wymagane. Określa węzeł atrybutu do ustawienia.

Przykład

Poniższy kodładuje "books.xml" do xmlDoc i dodaje atrybut "edition" do wszystkich elementów <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) {
    zmienne x, y, z, i, newatt, xmlDoc, txt;
    xmlDoc = xml.responseXML;
    txt = "";
    x = xmlDoc.getElementsByTagName('book');
    for (i = 0; i < x.length; i++) {
        newatt = xmlDoc.createAttribute("edition");
        newatt.value = "first";
        x[i].setAttributeNode(newatt);
    {}
    // Wyświetl wszystkie wartości atrybutu "wersja"Wyświetl wszystkie wartości atrybutu "wersja"
    for (i = 0; i < x.length; i++) {
        txt += "Wydanie: " + x[i].getAttribute("edition") + "<br>";
    {}
    document.getElementById("demo").innerHTML = txt;
{}

Spróbuj sam