I'm making a Tic-Tac-Toe game. My problem is that my code allows to rewrite X or O even if one of the squares already contain X or O. I'm using an if statement to write either X or O depending on a number variable that increases by one every time. I would like to add another conditional that only allows X or O to be written if my tag is empty. How do i do this?. Note: Only javascript please, since I haven't started learning jQuery yet. Thanks a bunch in advance!
var tds = document.querySelectorAll("td");
var player = 1;
var str = "";
for (var i = 0; i < tds.length; i++) {
tds[i].addEventListener("click", function() {
if (player % 2 === 0 && tds[i] !== "<td>X</td>" && tds[i] !==
"<td>O</td>") {
this.textContent = "O";
} else if (player % 2 !== 0 && tds[i] === "") {
this.textContent = "X";
}
player++;
});
}
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
You could just check the childNodes
property of an element, which returns a Nodelist
.
If it's length is 0, then your element is empty.
const elem = document.querySelector("#container")
console.log(!!elem.childNodes.length) // bang bang, u're boolean
// logs: false
<div id="container"></div>
Careful as line breaks count as text
though.