Reading XML Attributes with getAttribute()

Use getAttribute() to read an attribute value from an XML element. The original example loads xml-sample3.xml, collects its <address> elements, and reads each element's type attribute.

const addresses = xmlDocument.getElementsByTagName('address');
const type = addresses[0]?.getAttribute('type');
console.log(type);
Table of Contents

Read One XML Attribute Top ↑

The XML document is loaded with XMLHttpRequest. After it has been parsed, call getAttribute('type') on an address element:

const request = new XMLHttpRequest();
request.open('GET', '../php_tutorial/xml-sample3.xml', true);
request.addEventListener('load', () => {
  const xmlDocument = request.responseXML;
  if (!xmlDocument) return;

  const addresses = xmlDocument.getElementsByTagName('address');
  console.log(addresses[0]?.getAttribute('type'));
});
request.send();

Read the Attribute from Every Address Top ↑

for (const address of addresses) {
  const value = address.getAttribute('type') ?? '';
  console.log(value);
}

If an attribute is not present, getAttribute() returns null.

Working Demo Top ↑

Demo: read XML attributes with getAttribute()

What Changed from the Original Code? Top ↑

The original example used an ActiveX fallback, a synchronous request, undeclared globals, and document.write(). The demo still performs the same task, but now uses an asynchronous request, block-scoped variables, and DOM output.

XML




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer