DOM manipulation on first selector only

3643 views javascript
3

Building a very basic TicTacToe: Click the desired cell; once for X, again for O, third time for blank. I can get a function to cycle through the choices but it only targets the first cell, no matter where I click.

var choices = ['_','X','O'];
var i = 0;
var cell = document.querySelector("td");

function add(){
 cell.innerHTML= choices[i];
  i++;
    if(i > 2){
  i = 0;
  }
}
td{
  width: 100px;
  height: 100px;
  text-align: center;
  font-size:3em;
 
}

#two, #five, #eight{
  border-right: solid black 1px;
  border-left: solid black 1px
}
#four, #six, #five{
  border-top: solid black 1px;
  border-bottom: solid black 1px
}
<table>
  <tr>
    <td class="cell" id ="one" onclick="add()"></td>
    <td class="cell" id="two" onclick="add()"></td>
    <td class="cell" id="three" onclick="add()"></td>
  </tr>
  <tr>
    <td class="cell" id="four" onclick="add()"></td>
    <td class="cell" id="five" onclick="add()"></td>
    <td class="cell" id="six" onclick="add()"></td>
  </tr>
  <tr>
    <td class="cell" id="seven" onclick="add()"></td>
    <td class="cell" id="eight" onclick="add()"></td>
    <td class="cell" id="nine" onclick="add()"></td>
  </tr>
</table>

answered question

1 Answer

13

Pass this to your add function, and that will contain the current element (or cell) you're clicking in.

var choices = ['_','X','O'];
var i = 0;

function add(cell){
 cell.innerHTML= choices[i];
  i++;
    if(i > 2){
  i = 0;
  }
}
td{
  width: 100px;
  height: 100px;
  text-align: center;
  font-size:3em;
 
}

#two, #five, #eight{
  border-right: solid black 1px;
  border-left: solid black 1px
}
#four, #six, #five{
  border-top: solid black 1px;
  border-bottom: solid black 1px
}
<table>
  <tr>
    <td class="cell" id ="one" onclick="add(this)"></td>
    <td class="cell" id="two" onclick="add(this)"></td>
    <td class="cell" id="three" onclick="add(this)"></td>
  </tr>
  <tr>
    <td class="cell" id="four" onclick="add(this)"></td>
    <td class="cell" id="five" onclick="add(this)"></td>
    <td class="cell" id="six" onclick="add(this)"></td>
  </tr>
  <tr>
    <td class="cell" id="seven" onclick="add(this)"></td>
    <td class="cell" id="eight" onclick="add(this)"></td>
    <td class="cell" id="nine" onclick="add(this)"></td>
  </tr>
</table>

posted this

Have an answer?

JD

Please login first before posting an answer.