Reputation: 21
I have a list with two items, I want to add additional items after the first item when the content is loaded. How is this done? I can add items, but they only show up on the end of the list. Do I have to call or use the list element array?
First I create the new list item (<li>
) and then I populate the list item with the content. But I think I need to define the position of the list item before or while I add the li item.
if(x > 0){
$('<li></li>').attr('id','liAdult_'+x).appendTo($("ul:#ulAdultList"));
//$("ul:#ulAdultList").add($('<li></li>').attr('id','liAdult_'+x)).after($('#liAdult_0'));
$('<img/>').attr({'id':'imgAdultAvatar_'+x,'src':'./images/person_20x20.jpg','class':'imgAvatar','title':'The persons avatar','alt':'Avatar Adults'}).appendTo($('#liAdult_'+x));
$('<span></span>').attr({'id':'sAdultFirstName_'+x,'class':'sAdultLine'}).html(xData.adults[x].personFirstName).appendTo($('#liAdult_'+x));
$('<span></span>').attr({'id':'sAdultLastName_'+x,'class':'sAdultLine'}).html(xData.adults[x].personLastName).appendTo($('#liAdult_'+x));
$('<span></span>').attr({'id':'sAdultParent_'+x,'class':'sAdultLine'}).html(xData.adults[x].guardianRole).appendTo($('#liAdult_'+x));
$('<span></span>').attr({'id':'sAdultCellPhone_'+x,'class':'sAdultLine'}).html(xData.adults[x].personCellPhone).appendTo($('#liAdult_'+x));
$('<input/>').attr({'id':'personId_'+x,'type':'hidden'}).val(xData.adults[x].personId).appendTo($('#liAdult_'+x));
$('<a></a>').attr({'id':'lnkAdultProfile_'+x,'href':'#','name':'lnkAdultProfile_'+x,'title':'Edit the adult profile'}).html('Profile').appendTo($('#liAdult_'+x));
}
Upvotes: 2
Views: 4552
Reputation: 630389
Instead of .appendTo()
which will add it to the end like you have:
$('<li></li>').attr('id','liAdult_'+x).appendTo($("ul:#ulAdultList"));
Use .insertAfter()
to stick it at the location you want, like this:
$('<li></li>').attr('id','liAdult_'+x).insertAfter("#ulAdultList li:first");
This will insert it after the :first
<li></li>
in that <ul>
.
Upvotes: 2
Reputation: 7966
To add a new item after the first one:
$('li:nth-child(1)').append('<li>New Item</li>');
Upvotes: 2