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


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


source


You can add something slightly different:



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

      

+2


source


Like this?

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

      

0


source


How about this:

ul.append("<li><div></div></li>").contents("li:last-child > div").get(0);

      

0


source


This, I think:

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

      

0


source


How about this:

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

      

0


source


just for completeness:

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

      

0


source


var div = ul.append("<li><div></div></li>").find('div').get(0);

      

I think what you are looking for.

0


source


My decision:

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

      

0


source







All Articles