Seems like document.querySelectorAll(‘.cell’) has nothing to select as you included the script to early in the html…
Try to put
<script src="script.js"></script>
after the end of the section-tag and it should work.
But IMHO: Try to figure out, at which time javascript is executed and why 😉
I’ve tried with this JavaScript code I’ve found on the net and modified a little a bit ( it still worked with the original HTML but not with mine ). Here is the link to the original code: link
This is my modified JavaScript code:
let currentPlayer = "X";
let player = 1;
document.querySelectorAll('.cell').forEach(cell => cell.addEventListener('click', handleCellClick));
function handleCellClick(clickedCellEvent) {
const clickedCell = clickedCellEvent.target;
if(clickedCell.innerHTML != "")
{
alert("Click somewhere else!");
handleCellClick();
}
handleCellPlayed(clickedCell);
}
function handleCellPlayed(clickedCell) {
clickedCell.innerHTML = currentPlayer;
player++;
handlePlayerChange();
}
function handlePlayerChange() {
if(player%2 == 1)
{
currentPlayer = "X";
}
if(player%2 == 0)
{
currentPlayer = "O";
}
}
And this is the new, HTML made by me, I’ve gave the same class="cell"
attribute to every DIV but still it doesn’t works. 🙁
<body>
<script src="script.js"></script>
<section>
<div class="board">
<div class="column1">
<div class="cell" id="11"></div>
<div class="cell" id="12"></div>
<div class="cell" id="13"></div>
<div class="cell" id="14"></div>
<div class="cell" id="15"></div>
</div>
<div class="column2">
<div class="cell" id="21"></div>
<div class="cell" id="22"></div>
<div class="cell" id="23"></div>
<div class="cell" id="24"></div>
<div class="cell" id="25"></div>
</div>
<div class="column3">
<div class="cell" id="31"></div>
<div class="cell" id="32"></div>
<div class="cell" id="33"></div>
<div class="cell" id="34"></div>
<div class="cell" id="35"></div>
</div>
<div class="column4">
<div class="cell" id="41"></div>
<div class="cell" id="42">X</div>
<div class="cell" id="43"></div>
<div class="cell" id="44"></div>
<div class="cell" id="45"></div>
</div>
<div class="column5">
<div class="cell" id="51"></div>
<div class="cell" id="52"></div>
<div class="cell" id="53">O</div>
<div class="cell" id="54"></div>
<div class="cell" id="55"></div>
</div>
</div>
</section>
</body>
You are missing Css. Please use css from your reference link
Thanks, yes the was the problem. 😀 I didn’t included the CSS, I was pretty confident that it didn’t cause the problem.
The JavaScript waits for the user to click on a DIV with the class=”cell” attribute, then it calls the handleCellClick function. I just didn’t knew I have to put the link to the end. 😀 Was this what you meant by “Try to figure out, at which time javascript is executed and why ;-)” ? Thanks again.