views:

3668

answers:

10

Hi,

How do I get the div from within this (the last) list item?

Currently I have this, which is just plain ugly...any suggestions on a cleaner selector/ solution?

var div = ul.append("<li><div></div></li>").contents("li:last-child")[0].children[0];

Thanks!

A: 

Like this?

var div = ul.append("<li><div></div></li>").contents("li:last-child > div")[0];
doekman
This returns the list item...
Kieron
A: 

What about this:

ul.append("<li><div></div></li>").contents("li:last-child > div").get(0);
Chatu
This returns the list item...
Kieron
+1  A: 

You could go about the adding a bit differently too:

var div = $('<div/>'); 
// do whatever you need to do with the div
$('<li/>').appendTo(ul).append(div);
Lindsay
A: 

This, I think:

var div = ul.append('<li><div></div></li>').find("li:last div");
Mark B
A: 

How about this:

 var div = $('<li><div/></li>').appendTo(ul).find('div');
brad
A: 

just for completeness:

var div = $('<div></div>').appendTo($("<li></li>").appendTo(ul));
Jimmy
A: 
var div = ul.append("<li><div></div></li>").find('div').get(0);

I think that's what you are looking for.

Manik
+1  A: 

Using an array-index returns just the HTMLElement object and so removes a lot of jQuery's useful functionality, so be careful with that. I would tend to approach it this way:

var div = $("<div/>").appendTo($("<li/>").appendTo(ul));

From innermost to outermost, this creates a list item, appends it to your list, creates a div, appends it to your new list element, and returns the div, still wrapped in jQuery goodness. If you like, you can append an array index to get just the HTMLElement:

var div = $("<div/>").appendTo($("<li/>").appendTo(ul))[0];
Ben Blank
A: 

My Solution is:

var div = ul.append("<li><div></div></li>").find("div:last");
Ata
A: 

I am trying to add the eq index of preloaded images after they have been appended to the dom. I tried using .index(this... and appending an appended dividers text with this info but for some reason it was not showing up in the appended divider. any suggestions? here is my code:

html head var images['image1.jpg....]

js file

var index = $('div>ul li').index(this) $('div>ul li').append(''); $('div#caption').text("Image#"+index);