Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery insert after the last element

I want to add elements after the last one. My current code

<div class="find"><div id="FirstElement"> /*First element loaded first */ </div><div>

$('#AddNextElement' + id).click(function (e) {
   $('<div id="NextElement' + id +'">' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement"));
}

Current it adds only it after the first element:

1 4 3 2

I want it to add after the last element every time:

1 2 3 4

I've followed these links and I didn't find what I'm looking for:

jQuery insertAfter last item

insertAfter specific element based on ID

jQuery: Add element after another element

Thank you in advance!.

How I fixed it:

$('#AddNextElement' + id).click(function (e) {
   $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>').insertAfter($("#FirstElement").parent().find('.Finder').last());
}

I found the .parent().find('.find').last(); then insert after the last

like image 515
Norris Avatar asked Nov 19 '14 07:11

Norris


People also ask

How do I append after an element?

First, select the ul element by its id ( menu ) using the getElementById() method. Second, create a new list item using the createElement() method. Third, use the insertAfter () method to insert a list item element after the last list item element.

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.

Which is the correct syntax to insert content after the div elements?

The jQuery after() method is used to insert content after the selected elements.

What is insertAfter in jQuery?

jQuery insertAfter() Method The insertAfter() method inserts HTML elements after the selected elements. Tip: To insert HTML elements before the selected elements, use the insertBefore() method.


2 Answers

Just you need last() method

$('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>')
.insertAfter($('[id^="NextElement"]').last());
like image 80
Bhojendra Rauniyar Avatar answered Sep 26 '22 22:09

Bhojendra Rauniyar


How about adding a class to all elements? It will be easier to find the last:

$('.element-class:last').after('<div class="element-class" id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>');

This of course means that your First element must also have the class:

<div class="element-class" id="FirstElement"> /*First element loaded first */ </div>
like image 31
Thanasis Pap Avatar answered Sep 24 '22 22:09

Thanasis Pap