firasKoubaa firasKoubaa - 3 months ago 9
CSS Question

How to clone an item of a list "li" several times with incremental ids and values

I need to create an automatic pagination bar wich loads its max from a variable called number for example :

number = 5

this is my initial pagination bar :

<ul class="pagination">

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

</ul>


I need to clone the "li" with the name =2 , and create 3 other "li" with incremntal name and content, to obtain finally that form:

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


So how can I select the second "li", clone it and create the next "li" with incremntal names and values?

createPagination:function (number) {

}

Answer

You can get last li and then use for loop to increment from name(number) of last li and create clones. After that you can set name of each clone as current value of counter in loop (also same for text of a element in li) and append it to ul.

var last = $('.pagination li').last();
var num = last.attr('name');

for (var i = num; i <= 5; i++) {
  if (i != num) {
    var clone = last.clone().attr('name', i);
    $(clone).find('a').text(i);
    $('ul').append(clone);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="pagination">
  <li class="page" name="1"><a href="#" class="is-active">1</a></li>
  <li class="page" name="2"><a href="#">2</a></li>
</ul>

Comments