Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Trying to Clone one Element but multiplies items cloned

I am trying to clone elements onclick one time only but multiple items are being cloned when I click continuously multiple times then multiple items created.

I don't understand why multiple items are created continuously. I only want items from the data-id should be appended one time even if I click it should be removed the cloned item. Also when we click appended items they should be removed.

$('.item-save').click(function() {
  $(this).toggleClass('productad')
  window.localStorage.setItem('test' + this.dataset.id, $(this).hasClass('productad'));
});

$('.item-save').each(function() {
  var id = 'test' + this.dataset.id;
  if (localStorage.getItem(id) && localStorage.getItem(id) == "true") {
    $(this).addClass('productad');
  }
});

$('.item-save').click(function() {
  var id = this.dataset.id;
  $(".item-save").attr("data-id", function() {
    var $button = $(this).clone();
    $button.appendTo('.item-append');
  });
});
.item-save {
  position: relative;
  display: block;
  font-size: 14px;
  margin: 5px;
  padding: 5px;
  background: #a5a5a5;
  text-align: center;
  cursor: pointer;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class='item-all'>
  <div class='item-save' data-id='123'>Save</div>
  <div class='item-save' data-id='124'>Save</div>
  <div class='item-save' data-id='125'>Save</div>
  <div class='item-save' data-id='126'></div>
</div>
<div class='item-append'></div>

Here is my code JsFiddle Demo

I work with localStorage function to store some value so that is important without removing localStorage is it possible to fix this issue Any help or advice is highly appropriated

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Get rid of the attr() function in your second click function.

Change this

$('.item-save').click(function() {
  var id = this.dataset.id;
  $(".item-save").attr("data-id", function() {
    var $button = $(this).clone();
    $button.appendTo('.item-append');
  });
});

To this

$('.item-save').click(function() {
     var $button = $(this).clone();
     $button.appendTo('.item-append');

});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!