Metodo XML DOM setAttributeNS()

Definizione e uso

setAttributeNS() Metodo per aggiungere un nuovo attributo (con spazio dei nomi).

Se l'elemento esiste già con un attributo che ha il nome o lo spazio dei nomi, il valore verrà modificato a value Parametri

Sintassi

elementNode.setAttributeNS(ns,name,value,
) Descrizione
ns Obbligatorio. Specifica l'URI del namespace del nome dell'attributo da impostare.
name Obbligatorio. Specifica il nome dell'attributo da impostare.
value Obbligatorio. Specifica il valore dell'attributo da impostare.

Esempio

Esempio 1

Il codice seguente carica "books_ns.xml" nella xmlDoc e aggiunge l'attributo "edition" al primo elemento <book>:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
       myFunction(this);
   }
};
xhttp.open("GET", "books_ns.xml", true);
xhttp.send();
function myFunction(xml) {
    var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("book")[0];
    var ns = "https://www.codew3c.com/edition/";
    x.setAttributeNS(ns, "edition", "first");
    document.getElementById("demo").innerHTML =
    x.getAttributeNS(ns,"edition");
}

Prova personalmente

Esempio 2

Il codice seguente carica "books_ns.xml" nella xmlDoc e modifica il valore di "lang" del primo elemento <title>:

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        myFunction(xhttp);
    }
};
xhttp.open("GET", "books_ns.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
    var x = xmlDoc.getElementsByTagName("title")[0];
    var ns = "https://www.codew3c.com/edition/";
    x.setAttributeNS(ns, "c:lang", "italian");
    document.getElementById("demo").innerHTML =
    x.getAttributeNS(ns, "lang");
}

Prova personalmente