LauraNMS LauraNMS - 3 months ago 13
jQuery Question

Getting attribute of xml child nodes in jQuery

I had to amend this question because I left out a piece of code that breaking things. I only want to look at the images for a certain church.

xml file:

<churches>
<church>
<data-name>germanevangelical</data-name>
<name>German Evangelical</name>
<address>501 Elm St.</address>
<opened>1887</opened>
<neighborhood>East</neighborhood>
<region>East</region>
<architecture>Gothic</architecture>
<denomination>Evangelical Lutheran</denomination>
<closed>2006</closed>
<image caption="Mary Smith">image_1_forweb.jpg</image>
<image caption="Mary Smith">image_2_forweb.jpg</image>
<image caption="Mary Smith">image_3_forweb.jpg</image>
</church>
... (more church nodes)
</churches>


I want to access the image captions with jQuery.

Here is my code, but it's returning "undefined" for the captions:

var cName = 'germanevangelical';
$.ajax({
type: "GET",
url: "churchdata.xml",
dataType: "xml",
success: function(xml) {
var name = $(xml).find("data-name"); //get church names from xml file
$(name).each(function(id, item) {
if ($(item).text() == cName) { //find the right church in the xml file
$(item).parent().find("image").each(function(id, node) {
console.log('id: ' + $(node).attr('caption'));//undefined
})
}//end if right church in xml file
})
}
});


Can anyone see what I'm doing wrong please?

Answer

There is a very small mistake in your ajax code while parsing, use $xml instead of $(xml) while finding "data-name". Please check below code.. Try to run your page in chrome and check if any errors in the developer tools, if there is any errors it wont work.

var cName = 'germanevangelical';  
$.ajax({
type: "GET",
    url: "churchdata.xml",
    dataType: "xml",
    success: function (xml) {
    var xmlDoc = $.parseXML(xml),
    $xml = $(xmlDoc);
    var name = $xml.find("data-name"); //get church names from xml file
        $(name).each(function(id,item) {
              if ($(item).text() == cName) {
                $(item).parent().find("image").each(function(id,node) { 
                    console.log('id: ' + $(node).attr('caption')); //undefined
                });
               }
        });
      }
 });