skip to Main Content

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


  1. You can use

     inner = document.getElementById("cell").value;
    

    inner.innerHTML =’X’;
    That should make the value of the button element be "X"

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. You could use event.target.id when you pass event in function,
    each button must have its own id.

    example:

     function XonSquare(event) {
            document.getElementById(event.target.id).innerHTML = "X";
          }
     <button id="cell1" onclick="XonSquare(event)">-</button>
        <button id="cell2" onclick="XonSquare(event)">-</button>
        <button id="cell3" onclick="XonSquare(event)">-</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search