Oleksandr IY
Oleksandr IY

Reputation: 3106

clone appends multiple times

I need to clone and append elements on button click. First time it works correctly, but on other adds click it adds 2, 4, 8 ... elements. I debuged element just right before append and it contains one copy of element and click event fires one only. So I am confused a bit of this behaviour

Fiddle is here

$(document).on('click', '.js-add-faq-row', function(){
    var faqc = $('.faqs-container');

    //
    var tl = $('[id *= "content_element_prototype"] .faqs-container .faq-container');
    var ctl = tl.clone();
    ctl.appendTo(faqc);
});

Upvotes: 0

Views: 130

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

It's because on each append you're adding a new .faq-container element. Then when you clone you grab all of them, so you're doubling the number of elements on each click of the button. Instead, just grab the first one:

var faqc = $('.faqs-container').first();

Updated fiddle

Upvotes: 4

Related Questions