FREE Web Template Download
HTML CSS JAVASCRIPT SQL PHP BOOTSTRAP JQUERY ANGULARJS TUTORIALS REFERENCES EXAMPLES Blog
 

XML DOM setAttributeNS() Method


Element Object Reference Element Object

Example

The following code fragment loads "books_ns.xml" into xmlDoc and adds an "edition" attribute to the first <book> 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("book")[0];
    var ns = "http://tutorials/edition/";
    x.setAttributeNS(ns, "edition", "first");
    document.getElementById("demo").innerHTML =
    x.getAttributeNS(ns,"edition");
}

Output:

first
Try it Yourself »

Definition and Usage

The setAttributeNS() method adds a new attribute (with a namespace).

If an attribute with that name or namespace already exists in the element, its value is changed to be that of the prefix and value parameter

Syntax

elementNode.setAttributeNS(ns,name,value)

Parameter Description
ns Required. Specifies the namespace URI of the attribute to set
name Required. Specifies the name of the attribute to set
value Required. Specifies the value of the attribute to set

Example

The following code fragment 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 = "http://tutorials/edition/";
    x.setAttributeNS(ns, "c:lang", "italian");
    document.getElementById("demo").innerHTML =
    x.getAttributeNS(ns, "lang");
}

Output:

italian
Try it Yourself »

Element Object Reference Element Object