laroy laroy -4 years ago 74
CSS Question

JS For-Loop Cloning Too Many Times

EDITED: (I identified the problem that was previously being discussed in the comments)

my code is as follows:

<script type="text/javascript">
for(var i=0; i<5; i++){
$(".image-wrap").clone().appendTo(".container").attr('id', ("reason" + i));
}

</script>


for some reason, when I use this approach, I get a div with class of "image-wrap" and ID of "reason0" as expected, but then there are two instances of "image-wrap" with "reason1" and then four instances of "image-wrap" with "reason2," and so on and so forth. What's wrong with my loop?

Answer Source

there are two instances of "image-wrap" with "reason1" and then four instances of "image-wrap" with "reason2," and so on and so forth

is because you have used $(".image-wrap").clone(). Actually, the script is targeting every instance of the class "image-wrap."

So, if you need to clone only the first instance of .image-wrap, then you could use the :first pseudo-selector. See the updated script below..

$(".image-wrap:first").clone().appendTo(".container").attr('‌​id', ("reason" + i));

Read more about :first pseudo-selector here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download