So I’m revising a tic-tac-toe game I made a while ago and I’m trying to figure out how to get rid of repetitive functions. Is there anyway to target a specific button based on which is clicked?
function XonCell() {
document.getElementById("cell").innerHTML = 'X'
}
<button id="cell" onclick="XonSquare()">-</button>
<button id="cell" onclick="XonSquare()">-</button>
<button id="cell" onclick="XonSquare()">-</button>
So how would I make it to if the first button was clicked X would replace the first button’s text and if the second was clicked X would replace the second button’s text, and so on for all the buttons?
All I need is for the X to appear on the button that is clicked without multiple functions. Is there any way to do this?
3
Answers
You can use
inner.innerHTML =’X’;
That should make the value of the button element be "X"
The whole point of HTML IDs is that they are unique, and therefore addressable. You’re giving all cells the same ID. You should give them all the same class, but unique IDs, so your function can change the appropriate ID’s content to an X.
You could use
event.target.id
when you pass event in function,each button must have its own id.
example: