Home > front end >  How to Clone items on Click function?
How to Clone items on Click function?

Time:10-13

I create some elements with local storage and it works fine but I want that items also should be cloned to a specific div tag.

here is my jsFidddle Code jsFiddle Demo

Now When I try to clone all element to <div class="all-items"></div> but it didn't work here is my code below

 $(function() {
  $('.mix').click(function() {
    $(this).toggleClass('selected')
    window.localStorage.setItem('test'   this.dataset.id, $(this).hasClass('selected'));
  });

  $('.mix').each(function() {
    var id = 'test'   this.dataset.id;
    if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
      $(this).addClass('selected');
    }
        });
  $(document).ready(function() {
    var e = $('.top-items');
    for (var i = 0; i < 5; i  ) {
      e.clone().insertAfter(e);
    }
});

and the HTML is here

<div class="top-items">
<div data-id="1" class="box p001 mix ">Div 1</div>
<div data-id="2" class="box p002 mix">Div 2</div>
<div data-id="3" class="box p002 mix">Div 2</div>
<div data-id="4" class="box p002 mix">Div 2</div>
<div data-id="5" class="box p002 mix">Div 2</div>
</div>

<div class="all-items"></div> //all elements should be clone here on click one by one

To achieve this i try on click function but it didn't give perfect solution so that i want when elements added they should be remove onclick from this <div class="all-items"></div> cloned tag.

any help or advice is highly appreciated.

CodePudding user response:

You can do something like this

let topItemsHTML = $(".top-items").html()
$(".top-items").html("");  // clear top-items div

$(".all-items").html(topItemsHTML)  // fill all-items with top-items

  • Related