XML DOM » Element » getAttribute

Syntax:
element.getAttribute(name)

This method returns a string containing the value of the specified attribute.

If the named attribute does not have a specified or default value, this method returns null.

Examples

Code:
XML:

<States>
   <State ref="FL" const="27">
      <name>Florida</name>
      <capital>Tallahassee</capital>
   </State>
   <State ref="IA" const="29">
      <name>Iowa</name>
      <capital>Des Moines</capital>
   </State>
</States>

JavaScript:

xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.load("states.xml");

states = xml_doc.getElementsByTagName("State");
n_states = states.length;
for (i = 0; i < n_states; i++)
{
   state = states.item(i);
   attr = state.getAttribute("ref");
   document.write(attr + "<br>");
}
Output:
FL
IA
Explanation:

This example uses the 'states.xml' file. Firstly a NodeList is created of all the 'State' elements, and then the code iterates through them getting the value of the 'ref' attribute of each.

Language(s): JavaScript XML