Fastest way to find the index of a child node in parent

前端 未结 9 1577
醉梦人生
醉梦人生 2020-12-13 07:06

I want to find the index of the child div that has the id \'whereami\'.

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 07:13

    Year 2020 - A solution if you're using Tables - Clean Vanilla JS approach

    Credit goes to: Alain Cruz

    Source: https://stackoverflow.com/a/58845058/3626361 (leave him an Up vote if it helped you)

    Question: How to return the row and column index of a table cell by clicking?

    const cells = document.querySelectorAll('td');
    cells.forEach(cell => {
      cell.addEventListener('click', () =>
        console.log("Row index: " + cell.closest('tr').rowIndex + " | Column index: " + cell.cellIndex));
    });
    
    0:0 0:1 0:2 0:3
    1:0 1:1 1:2 1:3
    2:0 2:1 2:2 2:3

    Cheers! Stefano

提交回复
热议问题