I'm having difficulty understanding why my code only runs once. I can click the first square that appears and the class changes, but it seems to stop there. I am trying to be able to click squares and have new ones appear and so on. I am unable to click the second square that is created. I've logged "totalSquares.length" as well as "i". "i" seems to be less than the length of totalSquares so I am unsure why my loop stops. I also have a Codepen link here. Thank you in advance. Let me know if you need more clarification.
HTML:
<body>
<h1>Test
<br>
Your
<br>
Aim
</h1>
<p>Score: </p><span id="score">0</span>
<div id="container">
<div id="square"></div>
</div>
<script src="script.js"></script>
</body>
JS:
let totalSquares = [];
const squares = document.getElementById("square");
const totalScore = document.getElementById("score");
const heading = document.querySelector("h1");
let score = 0;
totalSquares.push(squares);
for (var i = 0; i < totalSquares.length; i++) {
totalSquares[i].addEventListener("click", function() {
createSquare();
this.classList.add("clicked");
score++;
totalScore.innerHTML = score;
console.log(totalSquares.length, i);
});
}
function createSquare() {
let div = document.createElement('div');
div.setAttribute("id", "square");
document.getElementById("container").appendChild(div);
totalSquares.push(div);
}