JQuery How to get a div in this code?
How do I get a div from this (last) list item?
I currently have this, which is just ugly ... any suggestions for choosing a selector / solution?
var div = ul.append("<li><div></div></li>").contents("li:last-child")[0].children[0];
Thank!
0
Kieron
source
to share
9 replies
Using an array index only returns the HTMLElement object and therefore removes a lot of useful jQuery functionality, so be careful with that. I would like to approach it like this:
var div = $("<div/>").appendTo($("<li/>").appendTo(ul));
From innermost to outermost, this creates a list element, adds it to your list, creates a div, adds it to your new list element, and returns a div still wrapped in jQuery kindness. If you like, you can add an array index to only get the HTMLElement:
var div = $("<div/>").appendTo($("<li/>").appendTo(ul))[0];
+1
Ben blank
source
to share
You can add something slightly different:
var div = $('<div/>');
// do whatever you need to do with the div
$('<li/>').appendTo(ul).append(div);
+2
Lindsay
source
to share
Like this?
var div = ul.append("<li><div></div></li>").contents("li:last-child > div")[0];
0
doekman
source
to share
How about this:
ul.append("<li><div></div></li>").contents("li:last-child > div").get(0);
0
Chatu
source
to share
This, I think:
var div = ul.append('<li><div></div></li>').find("li:last div");
0
Mark bell
source
to share
How about this:
var div = $('<li><div/></li>').appendTo(ul).find('div');
0
brad
source
to share
just for completeness:
var div = $('<div></div>').appendTo($("<li></li>").appendTo(ul));
0
Jimmy
source
to share
var div = ul.append("<li><div></div></li>").find('div').get(0);
I think what you are looking for.
0
Manik
source
to share
My decision:
var div = ul.append("<li><div></div></li>").find("div:last");
0
Ata
source
to share