How to set eventListener for table of buttons with no unique id for each one

I’m trying to make a battleship game, the table is made up by 10 rows and 10 columns of buttons with no unique id for each

      <table id="myTable">
          <tr >
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
          </tr>
          <tr >
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
            <td><button type="button"></button></td>
          </tr>
<!-- it's quite longer-->
</table>

to get the coordinates of the cell when any button is clicked, I did this
but I returns

table.addEventListener("click",function(){
  let col=this.closest('td').index();
  let row=col.closest('tr').index();
  shot([row,col]);
});

but the console throws typeError for this keyword

Uncaught TypeError: Cannot read property ‘index’ of null

Hi,
Your table has an id. Why don’t you use that.Plus, I ran your code, index properties don’t go with the table element. There are some other things you need. I have tried the code below, check it out:


myTable.addEventListener("click",function(e){
  let col=e.target.closest('td');
  let cIndex = col.cellIndex;
  let rIndex = col.parentElement.rowIndex;
  console.log(cIndex,rIndex);
  //shot([row,col]);
});
1 Like

what is the e here ? so I can look for document or something

Hey,
e represents the event that has occurred.

okay could you supply a document for it
:sweat_smile: please

okay I went through the following links to get to this solution:

https://www.w3schools.com/jsref/prop_tabledata_cellindex.asp
https://www.w3schools.com/jsref/prop_tablerow_rowindex.asp

You can read about the addEventListener method and its event handler from this link:

Hope that helps!