我可以使用querySelectorAll获取单元格索引吗?

问题描述 投票:0回答:2

我正在使用

forEach
运行
document.querySelectorAll()
循环,我需要获取每个节点的索引。最好的方法是什么?

javascript arrays
2个回答
0
投票

index
始终是
forEach
循环中的第二个参数。

const elements = document.querySelectorAll('your-selector');

elements.forEach((element, index) => {
  console.log(`Element: ${element}, Index: ${index}`);
  // Your code here
});

0
投票

您可以使用 foreach 第二个参数来获取数组中的单元格索引:

cellsArray.forEach((cell, index) => {
                   //...
                   console.log('Cell id: ', index)) }
© www.soinside.com 2019 - 2024. All rights reserved.