Método setAttributeNode() del DOM XML

Definición y uso

setAttributeNode() Método para agregar un nuevo nodo de atributo.

Si el elemento ya tiene un atributo con el mismo nombre, lo reemplazará con el nuevo atributo.

Si el nuevo atributo reemplaza un atributo existente, devuelve el nodo de atributo reemplazado, de lo contrario devuelve null.

Sintaxis

elementNode.setAttributeNode(att_node)
Parámetros Descripción
att_node Obligatorio. Especifica el nodo de atributo que se debe establecer.

Ejemplo

El siguiente código carga "books.xml" en xmlDoc y agrega el atributo "edition" a todos los elementos <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, 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);
    }
    // Salida de todos los valores del atributo "versión"Salida de todos los valores del atributo "versión"
    for (i = 0; i < x.length; i++) {
        txt += "Edición: " + x[i].getAttribute("edition") + "<br>";
    }
    document.getElementById("demo").innerHTML = txt;
}

Prueba personalmente