XML DOM setAttributeNS() Method

Definition and Usage

setAttributeNS() Method to add a new attribute (with namespace).

If an attribute with the same name or namespace already exists in the element, its value will be changed to value Parameters.

Syntax

elementNode.setAttributeNS(ns,name,value,
) Description
ns Required. Specifies the URI of the namespace for the attribute to be set.
name Required. Specifies the name of the attribute to be set.
value Required. Specifies the value of the attribute to be set.

Instance

Example 1

The following code loads "books_ns.xml" into xmlDoc and adds the "edition" attribute to the first <book> element:

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");
}

Try It Yourself

Example 2

The following code loads "books_ns.xml" into xmlDoc and changes the "lang" value of the first <title> element:

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");
}

Try It Yourself