<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<div class="outerContainer">
<div class="innerContainer">
<div class="test">test</div>
</div>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
for(let i=1;i<5;i++) {
$( ".test" ).clone().appendTo( ".innerContainer" );
}
});
</script>
</body>
</html>
Desired output:
<div class="outerContainer">
<div class="innerContainer">
<div class="test">test</div>
<div class="test">test</div>
<div class="test">test</div>
<div class="test">test</div>
<div class="test">test</div>
</div>
</div>
Instead I get way more elements, almost 20. I am new to jQuery and learning. I looked into jQuery.each() but it seems that method is geared toward use with arrays + objects.
Also, I am using jQuery because I need to attach eventListeners to all the cloned elements and event delegation is not possible because the elements are not within a parentContainer.
I am also currently testing to see If I can instead use a regular for-loop with cloneNode() which works to append my elements and then possibly using jQuery.each() to attach the eventListeners?