Reputation: 111040
I have an UL:
<ul id="news-feed">.....</ul>
I'd like to be able to append a LI to the top of the list and have that appended item slideDown into place.
$("#news-feed").append('<li">This is my item</li>').hide().slideDown();
Problem I'm having is the above code is sliding the news-feed item down, and not the appended item. Any ideas?
Upvotes: 4
Views: 3114
Reputation: 322562
If you were hoping to chain it all together, you can use appendTo()
instead. It will return the new <li>
element so you can slide it down.
$('<li>This is my item</li>').appendTo("#news-feed").hide().slideDown();
EDIT: As @cletus noted, you should use .prependTo()
as he did in his answer instead of .appendTo()
. This will bring the new item to the top of the list.
Upvotes: 7
Reputation: 625307
If you want to chain it together nicely, flip it around and use prependTo()
instead of prepend()
. Either:
$("<li>").text("This is my item").hide().prependTo("#news-feed").slideDown();
or
$("<li>This is my item</li>").hide().prependTo("#news-feed").slideDown();
I prefer the first because it handles escaping. The second doesn't. But it's largely a matter of preference.
Upvotes: 5
Reputation: 3200
Usually we take it this way:
var newsItem = $("<ul></ul>"); // Create a template item and clone from it
var parentItem = $( /* whatever selector string */ );
// …
newsItem.clone().text("blah").hide().appendTo(parentItem).toggle('slide');
Also, when you say “add to the top of the list”, usually prepend()
works better as expected.
Upvotes: 3
Reputation: 21848
Yes, first you need to make it display none, then make it slide down:
$("#news-feed").append('<li style="display:none">This is my item</li>').find('li:last').slideDown();
If that doesn't work, break it into two statements:
$('#news-feed').append('<li style="display:none">This is my item</li>');
$('#news-feed li:last').slideDown();
Upvotes: 1