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);
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();
for (const address of addresses) {
const value = address.getAttribute('type') ?? '';
console.log(value);
}
If an attribute is not present, getAttribute() returns null.
Demo: read XML attributes with getAttribute()
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.