user1692333
user1692333

Reputation: 2597

How to access element in object?

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

Answers (5)

Roko C. Buljan
Roko C. Buljan

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

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

Narek
Narek

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

S&#233;bastien Renauld
S&#233;bastien Renauld

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

PSR
PSR

Reputation: 40358

try this

my_ul.find('li:last');

Upvotes: 0

Related Questions