Insert jQuery after last element
I want to add items after the last. 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 only adds after the first element:
1 4 3 2
I want it to be added after the last item every time:
1 2 3 4
I followed these links and I did not find what I was looking for:
insertAfter specific item based on identifier
jQuery: add item after another item
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 .parent (). find ('. find'). last (); then paste after the last
How to add a class to all elements? It will be easier to find the latter:
$('.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 a class:
<div class="element-class" id="FirstElement"> /*First element loaded first */ </div>
HTML:
<div id="FirstElement"> First element loaded first </div> <div id="AddNextElement">Click me</div>
JS:
var current = 0; $('#AddNextElement').click(function (e) { var $el = (current == 0) ? $("#FirstElement") : $("#NextElement"+current); current++; $('<div id="NextElement' + current +'">Other element '+current+'</div>').insertAfter($el); });
Try yourself on jsfiddle
one way is to save the last item.
<div id="FirstElement"> /*First element loaded first */ </div> var lastElement = $('#FirstElement'); $('#AddNextElement' + id).click(function (e) { var element = $('<div id="NextElement"' + id +'>' + /*Add after the last element*/ + '</div>')); element.insertAfter(lastElement); lastElement = element; }
You can try under the code, it will add a new div after the last "NextElement" div
JS Code:
$(function(){ $('#AddNextElementButton').on("click", function (e) { var id = $("[id^='NextElement']").length ? $("[id^='NextElement']").length+1 : 1; if($("[id^='NextElement']").length){ $('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('[id^="NextElement"]').last()); } else { $('<div id="NextElement'+ id +'">Add after the last element</div>').insertAfter($('#FirstElement')); } }); });