Search code examples
javascriptjqueryclone

Trying to clone an HTML class using jquery but each method I use the clone copies an infinite number of times


first time, dev student at uPenn. I'm cloning an HTML element successfully but I can't get it to clone the number of times of an array's index using .length. Here is what I have so far that is giving me infinite clones, thanks for any help:

$(function() {
console.log( "jquery, ready!" );

var usTime = ["9am", "10am", "11am", "12pm", "1pm", "2pm", "3pm", "4pm", "5pm"];
var militaryTime = [9, 10, 11, 12, 13, 14, 15, 16, 17];

    for (var i = 0; i < usTime.length; i++){
    $("section").clone().appendTo("main");}

})

Solution

  • Every iteration you select all the section elements. So each loop you select the ones you just added. Select it once and clone that each time.

    var section = $("section");
    for (var i = 0; i < usTime.length; i++){
      section.clone().appendTo("main");
    }