tags:

views:

84

answers:

2

If content is added to the DOM using, e.g.,

$("ul").append("<li>test</li>");

how does one get a reference the content just added w/o having to select the newly added content?

Assigning the return value from the append() method is the jQuery object.

var newContent=$("ul").append("<li>test</li>");

One could do

var newContent=$("ul li:last");

but is there a way to get it more directly?

Thanks

+3  A: 

You can create it in its own line ala:

var newLi = $('<li>test</li>');
$('ul').append(newLi);

//Continue using newLi and it will affect the appended element
Michael La Voie
The limitation of this approach is you have to create a local variable and than perform execute additional methods on it. I was hoping for a way to create the new element and "chain" methods to is all at once.
ChrisP
+7  A: 

Use .appendTo().

micahwittman
Seconded... this makes for a lot less confusion.
prodigitalson
If you use `.appendTo()` keep in mind that the order is reversed, unlike a regular `.append()` so it'd be `$("content to append").appendTo("#selector");`
Ariel
Although the answer below works, this answer provides more flexibility and less code. The main reason is you can easily chain additional methods on the same line. Thanks!
ChrisP