Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add an element always as last element using jquery?

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?

like image 923
user811433 Avatar asked Aug 12 '11 05:08

user811433


People also ask

Is jQuery the last element?

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.

How do I append my last child?

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.

Is last child jQuery?

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.

How do I get the second last Li in jQuery?

You need to use "nth-last-child(2)" of jquery, this selects the second last element.


2 Answers

$('#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>')

like image 142
rkw Avatar answered Nov 03 '22 09:11

rkw


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);
like image 33
jfriend00 Avatar answered Nov 03 '22 10:11

jfriend00