Vanilla JS-使用HTMLCollection中的特定(唯一)类获取Element的索引

问题描述 投票:0回答: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类的元素的索引。

javascript html ecmascript-6 htmlcollection
1个回答
0
投票

如果我没有正确理解,您想将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
© www.soinside.com 2019 - 2024. All rights reserved.