firasKoubaa firasKoubaa - 3 months ago 11
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>

<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>
</li>
</ul>


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);
$(cloned).find('a').text(i);
$('ul').append(cloned);
}
}
}


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

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);
        cloned.find('a').text(i);
        nextLI.before(cloned);
    }
}

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).