0

Xml:

<Data>
   <Cat>
      <Name>Fluffy</Name>
   </Cat>

   <Cat>
      <Name>Willy</Name>
   </Cat>
</Data>

JQuery:

// ...Some ajax calls...
$(xml).find('Cat').each(function() {
   var name = $(this).find('Name').text();
   alert(name);
});

How can I store the results of find('Cat') in a variable, so that I can pass it to a function and handle it there? I thought something like this, but it doesn't work:

var cats = $(xml).find('Cat');
ShowCatNames(cats);

...

function ShowCatNames(cats) {
   $(cats).each(function() {
       var name = $(this).find('Name').text();
       alert(name);
   }
}

Thank you.

1 Answer 1

1

Try parsing the xml first

var cats = $($.parseXML(xml)).find('Cat');
Sign up to request clarification or add additional context in comments.

4 Comments

Hi. I have specified in my AJAX call a dataType of "xml". However, I was only able to get your code to work if I specified the dataType as "text". I have read that specifying xml returns the same XmlDocument that you would get after calling .parseXML. Do you know why this wouldn't work when I set my dataType as xml? I was thinking that if I just set the dataType to xml, then I wouldn't have to call .parseXML
@Eric Try doing a console.log(xml) to see if you get an XmlDocument
Yes, actually, I just looked and it is an XmlDocument (it actually just says Document, but it is the same as when I call .parseXML, as far as I can tell.
Ok, oddly enough, my original code is working now. I'll mark your answer, since it worked, as well. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.