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?
The last() function is an inbuilt function in jQuery which is used to find the last element of the specified elements. Here selector is the selected elements. Parameters: It does not accept any parameter. Return value: It returns the last element out of the selected elements.
To insert element as a last child using jQuery, use the append() method. The append( content ) method appends content to the inside of every matched element.
It is a jQuery Selector used to select every element that is the last child of its parent. Return Value: It selects and returns the last child element of its parent.
You need to use "nth-last-child(2)" of jquery, this selects the second last element.
$('#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>')
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With