1

在标题中。

HTML:

<div class="active"></div>
<div></div>
<div></div>

Javascript(原版):

// source HTML collection, only get the elements index which has the class "active"
let theCollection = document.querySelectorAll('div'); 

// related HTML collection
let anotherCollection = document.querySelectorAll('div .anotherClass');
// adding the class the corresponding element
theCollection[index].classList.add('active');

我需要得到的是当前具有active该类的元素的索引theCollection

4

2 回答 2

1

要完成您的任务:

“我需要得到的是当前在集合中具有活动类的元素的索引。”

您可以遍历 div 并检查哪个 div 具有活动类。请运行代码进行验证。

document.querySelectorAll('div').forEach((item, index) => {
  if (item.classList.contains('active')) {
    document.getElementById('showActiveIndex').textContent = `index is ${index}`;
  }
})
<div>zero</div>
<div>one</div>
<div class="active">two</div>
<div>three</div>
<hr />
<div id="showActiveIndex"></div>

于 2019-11-14T14:50:22.490 回答
0

如果我理解正确,您希望将课程附加active到拥有课程div的人之后。divactive

为什么不直接选择所有对应的 div 并直接将活动类添加到它们?

document.querySelectorAll('div.active + div').classList.add('active'); // selects all the div that comes after divs who have the .active class
于 2019-11-14T14:45:19.080 回答