Reputation:
I'm trying to pull some information using the wikipedia API. The response is a mega-string with all of the HTML for a section. In the response, I'm wanting to extract the first 3 li
's out of the first ul
, and preferably don't want to write it to document until I'm done extracting.
I've been tinkering with different combinations of jquery functions, but haven't had much luck. What made the most sense to me was something like:
var markup = $('<div>' + response + '</div>').find('ul:lt(3)').html();
$('body').append(markup);
Only the :lt()
filter only seems to apply to the ul
and not the li
's even though .find()
only selects the descendants. I'm probably overthinking this, but do you guys have any ideas?
Upvotes: 0
Views: 51
Reputation: 150010
You can do it in several ways, e.g., first .find()
the ul element and then get some of its .children()
:
var markup = $('<div>' + response + '</div>').find('ul:first')
.children('li:lt(3)').html();
...or use a different selector:
.find('ul:first > li:lt(3)').html()
From your comment:
"How would I go about select the ul AND the first the li's instead of just the li's?"
If you select the ul it will automatically include all of its children (that is, the resulting jQuery object will contain one element, the ul, but the ul will retain its children), so you could just delete the unwanted children:
var markup = $('<div>' + response + '</div>').find('ul:first');
markup.children('li:gt(2)').remove();
$('body').append(markup);
Notice that in that latest code I did not use the .html()
method, because that would just extract the contents of the ul, i.e., the li elements, and not the ul element itself.
Upvotes: 2