Charlotte Dann
Charlotte Dann

Reputation: 298

Using a link's id to parse data from an xml file with jquery

the xml is like this

<post id="1">
  <content>...</content>
</post>
<post id="2">
  <content>...</content>
</post>
<post id="3">
  <content>...</content>
</post>

and then the html is

<div id="content"></div>
<a id="1">option 1</a>
<a id="2">option 2</a>
<a id="3">option 3</a>

I'm trying (and failing) to replace whatever's in the div with the 'content' of a post when you click on its corresponding link- and the ids are not always numbers. I think I need to use event.target.id but can't find info on this anywhere on the web, thanks for your help.

Upvotes: 0

Views: 248

Answers (2)

jondavidjohn
jondavidjohn

Reputation: 62392

try

$('#content a').click(function() {
    var id = this.id;
    $.ajax({
        type: "GET",
        url: "xml_file.xml",
        dataType: "xml",
        success: function(xml) {
            $('#'+id).html(xml.find('#'+id).html());
        }
    });
    return false;
}

This should replace all html content from with in a <post id="X"> and place it inside #content when <a id="X"> is clicked.

also don't forget to return false to prevent the default action of <a>

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185923

$('a').click(function() {
    var id = this.id;
    $.get("http://www.foo.com/xmlfile.xml", function(xml) {
        var content = $(xml).find('post#' + id + ' content').text();
        $('#content').html(content);
    });
});

Upvotes: 3

Related Questions