Nathan Clarke
Nathan Clarke

Reputation: 13

Javascript XML object - Undefined

The following code brings back my id.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
  }
};
xhttp.open("GET", "https://brewslocal.com/brewery-images-xml", true);
xhttp.send();

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  document.getElementById("photoBox").innerHTML = xmlDoc.getElementsByTagName("image")[0].id;
}
<div id="photoBox"></div>

When I change to the next attribute imageurl it comes back undefined.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    myFunction(this);
  }
};
xhttp.open("GET", "https://brewslocal.com/brewery-images-xml", true);
xhttp.send();

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  document.getElementById("photoBox").innerHTML = xmlDoc.getElementsByTagName("image")[0].imageurl;
}
<div id="photoBox"></div>

Any ideas?

Upvotes: 0

Views: 739

Answers (2)

Rahul Patil
Rahul Patil

Reputation: 169

You can do like this

function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName('title')[0];
var y = x.childNodes[0];
document.getElementById("demo").innerHTML =
y.nodeValue; 

}

Upvotes: 0

Alexander Staroselsky
Alexander Staroselsky

Reputation: 38767

You can use Element.getAttribute('attributeName') to get the attribute value from this custom HTML element.

function myFunction(xml) {
  var xmlDoc = xml.responseXML;
  document.getElementById("photoBox").innerHTML = xmlDoc.getElementsByTagName("image")[0].getAttribute('imageurl');
}

Upvotes: 4

Related Questions