Reputation: 2597
For example i have:
var my_ul = jQuery('<ul/>');
jQuery('<li/>').appendTo(my_ul);
jQuery('<li/>').appendTo(my_ul);
jQuery('<li/>').appendTo(my_ul);
jQuery('<li/>').appendTo(my_ul);
Is it possible to access last li in ul?
Upvotes: 0
Views: 51
Reputation: 206669
var my_ul = $('<ul/>');
for(i=0;i<4;i++){
my_ul.append("<li> index: "+i+"</li>");
}
alert( my_ul.find('li:last').text() ); // .find() faster than constructor
Upvotes: 0
Reputation: 50643
You can do it like this:
my_ul.find('li:last');
Or alternatively, you can use context parameter of jquery constructor:
$('li:last', my_ul);
See demo
Upvotes: 3
Reputation: 3823
var my_ul = jQuery('<ul/>');
x1 = jQuery('<li/>').appendTo(my_ul);
x2 = jQuery('<li/>').appendTo(my_ul);
x3 = jQuery('<li/>').appendTo(my_ul);
x4 = jQuery('<li/>').appendTo(my_ul);
x4.html('I\'m last');
You can access what element you want.
Upvotes: 0
Reputation: 19672
Naturally!
This is the real magic behind jQuery: selectors. I strongly recommend you to read up on all of them, as they all have a purpose, and some of them are pretty, pretty powerful. If you're into performance/optimization, also make a note of the emulated pseudo-selectors, as they're usually slower.
To answer your question directly, all of the following code will get you the last item in your ul:
my_ul.children("li:last");
my_ul.children("li").last();
Exercise for the reader: find which one is more performant :-)
Upvotes: 0