标题中。
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
类的元素的索引。
如果我没有正确理解,您想将active
类附加到具有active
类的div之后的div中。为什么不只选择所有应用的div并直接向它们添加活动类呢?例如:
let theCollection = document.querySelectorAll('div');
theCollection.querySelectorAll('div.active + div').classList.add('active'); // selects all the div that comes after divs who have the .active class