Search code examples
javascripthtmlclickcell

Get the value of the next table cell onclick javascript


I am trying to get the value of the cell right of the cell where i click.

But right now I get the value of the cell I want, but I can click any cell in that row and get the desired value. But it should only be possible with the first column. So I click the any cell in the first column and I wanna get it's next neighbour cell value.

document.querySelector("#tableEventListId").addEventListener("click",event => {
        let dataTr = event.target.parentNode;
        let deleteEventId = dataTr.querySelectorAll("td")[1].innerText;
        console.log(deleteEventId);
        alert(deleteEventId);

Any help?


Solution

  • You can use nextElementSibling

    document.getElementById('table1').onclick = function(event){
      //REM: Target
      var tElement = event.target;
    
      if(
        //REM: Only cells (=<td>)
        tElement.tagName === 'TD' &&
        
        //REM: Only first column cells
        tElement.parentNode.firstElementChild === tElement
      ){ 
        //REM: Next Elementsibling of Target or Null
        var tNext = tElement.nextElementSibling;
          
        if(tNext){
          console.log('TD: ', tElement.textContent);
          console.log('Next: ', tElement.nextElementSibling.textContent)
        }
      }
    }
    table, td{
      border: 1px solid black
    }
    <table id = 'table1'>
      <thead>
        <tr>
          <th>A</th>
          <th>B</th>
          <th>C</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>A1</td>
          <td>B1</td>
          <td>C1</td>
        </tr>
        <tr>
          <td>A2</td>
          <td>B2</td>
          <td>C2</td>
        </tr>
        <tr>
          <td>A3</td>
          <td>B3</td>
          <td>C3</td>
        </tr>
      </tbody>
    </table>