jonnyhitek
jonnyhitek

Reputation: 1551

Retrieving one element from jQuery each function

basically I am parsing a xml file and retrieving 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.

Upvotes: 0

Views: 1363

Answers (1)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

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.

Upvotes: 1

Related Questions