Limit the number of elements from an AJAX response
AJAX response returns a list of <a> elements:
<a href="/1/">One</a> <a href="/2/">Two</a> <a href="/3/">Three</a> How to select only the first n a elements from the answer?
$.ajax({ url: '/' + page, success: function (res) { btn.after($('a', $(res)).slice(0,20)); } }); What I'm trying now, but getting Uncaught Error: Syntax error, unrecognized expression , followed by the whole answer.
Here is what I would do:
$.ajax({ url: '/' + page, success: function (res) { btn.after(res.split('</a>').splice(0, num).join('</a> ') + '</a>'); } }); It breaks it and returns only those elements that you want.
JSFiddle: http://jsfiddle.net/howderek/VamZt/
The problem is that the context selector does not return anything. A simple test shows this.
console.log($('a', $(res))) Break it into pieces. You need to use a filter for content that is returned from the server, because this is a list of anchors.
var content = $(res); var anchors = content.filter("a"); var anchorLimit = anchors.slice(0,20); btn.after(anchorLimit); Another option is to do what you did, but wrap it in a div.
$('a', $("<div>" + res + "</div>"))