skip to Main Content

I’m running a forEach loop using document.querySelectorAll(), and I need to get the index of each node. What would be the best way to do this?

function queryFunc(query, func){
    document.querySelectorAll(query).forEach(func);
};

queryFunc(".fooBar", function(e){
    //I need to return the index of the cell that called the function.
});

3

Answers


  1. index is always the second parameter in a forEach loop.

    const elements = document.querySelectorAll('your-selector');
    
    elements.forEach((element, index) => {
      console.log(`Element: ${element}, Index: ${index}`);
      // Your code here
    });
    

    Based on your edit, here is how you can call the index argument from the external function.

    function queryFunc(query, func){
        document.querySelectorAll(query).forEach((element, index) => {
            func(element, index);
        });
    };
    
    queryFunc(".fooBar", function(e, index){
        console.log('Cell index: ' + index);
    });
    
    Login or Signup to reply.
  2. You can use foreach second argument to obtain cell index in the array:

    cellsArray.forEach((cell, index) => {
                       //...
                       console.log('Cell id: ', index)) }
    
    Login or Signup to reply.
  3. If you mean the cellIndex of an HTMLTableCellElement, you can simply use the cellIndex property:

    document.querySelectorAll("td").forEach(td => console.log(td.cellIndex))
    <table>
      <tr>
        <td>r1c1</td>
        <td>r1c2</td>
        <td>r1c3</td>
       </tr>
       <tr>
        <td>r2c1</td>
        <td>r3c2</td>
        <td>r3c3</td>
       </tr>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search