Limit number of elements from AJAX response

Viewed 463

The AJAX response returns a list of <a> elements:

<a href="/1/">One</a>
<a href="/2/">Two</a>
<a href="/3/">Three</a>

How do I select only the first n a elements from the response?

$.ajax({
    url: '/' + page,
    success: function (res) {
        btn.after($('a', $(res)).slice(0,20));
    }
});

That's what I'm currently trying but I'm getting a Uncaught Error: Syntax error, unrecognized expression followed by the whole response.

3 Answers

Here is what I would do:

$.ajax({
    url: '/' + page,
    success: function (res) {
        btn.after(res.split('</a>').splice(0, num).join('</a> ') + '</a>');
    } });

It splits it and only gives back the elements you want.

JSFiddle: http://jsfiddle.net/howderek/VamZt/

The problem you have is the fact that the context selector returns nothing. A simple test shows it.

console.log($('a', $(res)))

Break it up into pieces. You need to use filter on the content that is return from the server because it is a list of anchors.

var content = $(res);
var anchors = content.filter("a");
var anchorLimit = anchors.slice(0,20);
btn.after(anchorLimit);

Other option is to do what you were doing, but wrap it in a div.

$('a', $("<div>" + res + "</div>"))

JSFiddle

Related