0

I'm loading xml and then getting data with js. My question is every time I need to find an attribute do I have to execute a function?

$(document).find("Item").each(function(){
}

I want to say

$(document).find("Item").eq(0).attr("title")

However this only works when I place it in the function

 function parse(document){
 }

This is my xml

 $.ajax({
    url: 'data.xml',
    dataType: "xml",
    success: parse,
    error: function(){alert("Error: Something wrong with XML");}
});
2
  • Question is a little unclear; what do you mean by "only works when I place it in a function"? My wild guess is that you have an issue with the scope of document. Commented Jun 13, 2013 at 1:27
  • @user2238083 - Please accept the answer, if the solution works for you. Commented Jun 17, 2013 at 15:58

1 Answer 1

1

You can use jQuery.parseXML

<html>

    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>

    <body>
        <p id="someElement"></p>
        <p id="anotherElement"></p>
        <script>
            var xml = "<rss version='2.0'><channel><title>RSS Title</title></channel></rss>",
                xmlDoc = $.parseXML(xml),
                $xml = $(xmlDoc),
                $title = $xml.find("title");

            /* append "RSS Title" to #someElement */
            $("#someElement").append($title.text());

            /* change the title to "XML Title" */
            $title.text("XML Title");

            /* append "XML Title" to #anotherElement */
            $("#anotherElement").append($title.text());
        </script>
    </body>

</html>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.