XML DOM getElementsByTagNameNS() method

Document Object Reference Manual

Definition and usage

The getElementsByTagNameNS() method can return a node list of all elements with specified name and namespace.

Syntax:

getElementsByTagNameNS(ns,name)
Parameter Description
ns A string value that can specify the namespace name. The value "*" can match all tags.
name A string value that can specify the tag name to be retrieved. The value "*" can match all tags.

Return value

A read-only array of Element nodes with specified namespace and local name in the document tree (technically, it is NodeList object).

Description

This method is similar to getElementsByTagName() methodSimilar, but it retrieves elements based on namespace and name. It is only used in XML documents with namespaces.

Instance

In all the examples, we will use the XML file books.xml, and the JavaScript function loadXMLDoc().

The following code snippet can add a namespace element node to each <book> element:

xmlDoc=loadXMLDoc("/example/xdom/books.xml");
var x=xmlDoc.getElementsByTagName('book');
var newel, newtext;
for (i=0; i<x.length; i++)
  {
  newel=xmlDoc.createElementNS('p', 'edition');
  newtext=xmlDoc.createTextNode('First');
  newel.appendChild(newtext);
  x[i].appendChild(newel);
  }
//Output all title and edition
var y=xmlDoc.getElementsByTagName("title");
var z=xmlDoc.getElementsByTagNameNS("p","edition");
for (i=0;i<y.length;i++)
  {
  document.write(y[i].childNodes[0].nodeValue);
  document.write(" - ");
  document.write(z[i].childNodes[0].nodeValue);
  document.write(" edition");
  document.write("<br />");
  }

Try It Yourself (TIY)

createElementNS() - Create element node with namespace(Not supported by IE browser)

Document Object Reference Manual