firasKoubaa firasKoubaa - 1 year ago 84
HTML Question

jQuery Clone several "li" and append at a specific position of ul (not its end)

am developping a dynamic pagination bar , where the "li" are cloned n times depending of a number received from an external webservice.

here is my pagination element:

<ul class="pagination">
<li class="pagePrevious" name="previous">
<a href="#" aria-label="Previous"> <span aria-hidden="true">«</span> </a>

<li class="page" name="1"><a href="#" class="is-active">1</a></li>

<li class="pageNext" name="next">
<a href="#" aria-label="Next"> <span aria-hidden="true">»</span> </a>

evidently you may note that my first Li and my last Li inside the Ul are the button next and previous which are not cloned and they are statically always present .

my cloning fonction consits of selecting the last-1 child of the li which is directly the second , and clone it with dynamic incremental id , and finally its inserts it in the ul.

my fonction :

createPagination: function (nb) {
var lastLI = $('.pagination li').last().prev();
var num = lastLI.attr('name');

for (var i = num; i <= nb ; i++) {
if (i != num) {
var cloned = lastLI.clone().attr('name', i);

my problem is how to make it append the cloned li always before the last li of next button. ???
note that i mays not change the name of class attribute for other specifications

Any suggestions ??

Answer Source

Use .before() to put something immediately before another element.

createPagination: function (nb) {
    var nextLI = $('pagination .pageNext');
    var lastLI = nextLI.prev();
    var num = lastLI.attr('name');

    for (var i = num+1; i <= nb ; i++) {
        var cloned = lastLI.clone().attr('name', i);

BTW, you don't need to write $(cloned), since cloned is already a jQuery object. And if you start the for loop at num+1, you don't need to check if (i != num).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download