tags:

views:

26

answers:

1

Hi,

basically I am parsing a xml file and retreving certain elements from that xml file using the each function. However I now need to just return the first value, not 'each' value. If anyone could help it would be awesome.

Code so far:

// basic ajax call to retrieve xml file - then on success sent over to checkNotDate function
$('#notifyBox').empty();
    $.ajax ({
        type: "GET",
        url: "anyFeed.xml",  
        datatype: "xml",
        success: checkNoteDate 
});
// parse xml and display in alert

function checkNoteDate (xml) {
    $(xml).find("entry").each(function()  
    {
        var $item = $(this);
        var title = $item.find("title").text();
        var link = $item.find("link").attr("href");
        var output = "<a href=\"" + link + "\" target=\"_self\">" + title + "<\/a>" + "<br />";
        alert(output);
    }); 
}

So all I need to do is just get the first value and save to a var. thanks in advance

+1  A: 

Just select the first element using find():

var $item = $(xml).find('entry:first');

Or using some similar syntax:

var $item = $(xml).find('entry').eq(0);
var $item = $('entry:first', xml);
var $item = $('entry', xml).eq(0);

All do the same thing.

Additionally, you could have just returned false at the end of the each statement, that would have caused the loop to stop after the first iteration. This would have had the same effect of manipulating only the first object, but it's of course cleaner to use the methods I mentioned above.

Tatu Ulmanen
Cheers Tatu I will be giving this a try this morning and let you know how I get along. Thanks a million
jonathan p
thanks dude got it - not sure if it is the neatest implementation but here's what worked below: function checkNoteDate (xml) { $(xml).find('entry:first') { var $item = $(this); var title = $item.find("title:first").text(); var link = $item.find("link:first").attr("href"); var output = "<a href=\"" + link + "\" target=\"_self\">" + title + "<\/a>" + "<br />"; alert(output); } } });
jonathan p
I'm surprised that that worked. You don't need to use `var $item = $(this)`, just do `var $item = $(xml).find('entry:first')`.
Tatu Ulmanen
yeh i used this in the end:noteDate = $(xml).find('entry:first published').text();thanks again
jonathan p