Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can I get cell index using querySelectorAll?

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.
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading