问题
I want a certain div to be added as the last element in a list no matter what. Is there any way in which I can explicitly specify this?
回答1:
Get the parent of the list and add the new item to that parent as the last child.
Using plain javascript:
parent.appendChild(newElement);
Mozilla documentation: https://developer.mozilla.org/En/DOM/Node.appendChild
If you want to add other items and still have this item be the last item, then you will have to add the new items before this last item or remove this item, append your new item, then append this one back again at the end.
Once you already have the last element in the list, if you then want to add a new element right before that last element, you can do it like this:
parent.insertBefore(newElement, parent.lastChild);
回答2:
$('#list').append('<div></div>')
will append it to the very end of the #list
If you want to append it to the very last div, just in-case there are other elements after that, then you can use $('#list div:last').after('<div></div>')
回答3:
If you want to absolutely make sure of that, place empty container with an ID and replace content inside if you need to up date it, so if you have a big container and then sub-containers within, the last child should be like so
HTML
<div id="parent">
<div id="child1"></div>
<div id="child2"></div>
<div id="child3"></div>
<div id="LastChild"></div>
</div>
now if you need to update,
jQuery
var newcontent = '<p id="newcontent">I am the new content</p>';
//Build your content as html or plain text
$('#LastChild').html(newcontent); //Replace old content in last child div with new
Now, if you wish to keep the old content from last child div and insert new below that you can do following
var newcontent = $('#LastChild').html();
var newcontent += '<p id="newcontent">I am the new content</p>';
$('#LastChild').html(newcontent);
Or, if you want to keep old content in last child div but have new content be displayed on top or before the old, you can just swap the order of var newcontent like so
var newcontent = '<p id="newcontent">I am the new content</p>';
var newcontent += $('#LastChild').html();
$('#LastChild').html(newcontent);
回答4:
When you are talking about list, I will assume you are referring to un-ordered lists.
You will need to so something of this sort:
$('ul').append('<li>Bottom list-item</li>');
来源:https://stackoverflow.com/questions/7036095/how-to-add-an-element-always-as-last-element-using-jquery