Reputation: 11
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);
}
Upvotes: 1
Views: 44
Reputation: 2812
document.getElementById
returns only 1 element.
So, you push a single element (squares
) into an array (totalSquares
).
So, it looks like the for loop runs totalSquares.length
times which must be 1.
If you have multiple elements with id square
, give them class square
instead & get all elements with document.querySelectorAll
like this:
const squares = document.querySelectorAll('.square');
Upvotes: 1
Reputation: 11
Thank you guys for the answers. I received some help and the code below accomplishes what I'm trying to achieve.
const squares = document.getElementById("square");
const totalScore = document.getElementById("score");
let score = 0;
function createSquare() {
let div = document.createElement('div');
div.setAttribute("id", "square");
div.addEventListener("click", function() {
this.classList.add("clicked");
score++;
totalScore.innerHTML = score;
createSquare();
});
document.getElementById("container").appendChild(div);
}
createSquare();
Instead of using a for-loop they suggested I put the eventListener directly in the createSquare function so this places an eventListener directly on the square.
Upvotes: 0