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