在 HTMLCollection 中获取具有特定(唯一)class 的元素索引
Get Index of Element with specific (unique) class in HTMLCollection
在标题中。
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');
我需要得到的是theCollection
.
中当前有active
class的元素的索引
如果我没理解错,你想将 active
class 附加到 div
之后的 div
,div
active
class.
为什么不直接 select 所有相应的 div 并直接将活动 class 添加到它们?
document.querySelectorAll('div.active + div').classList.add('active'); // selects all the div that comes after divs who have the .active class
完成你的任务:
"What I need to get is the index of the element which currently has the active class within theCollection."
您可以遍历 div 并检查哪个 div 具有活动的 class。请运行验证码
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>
在标题中。
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');
我需要得到的是theCollection
.
active
class的元素的索引
如果我没理解错,你想将 active
class 附加到 div
之后的 div
,div
active
class.
为什么不直接 select 所有相应的 div 并直接将活动 class 添加到它们?
document.querySelectorAll('div.active + div').classList.add('active'); // selects all the div that comes after divs who have the .active class
完成你的任务:
"What I need to get is the index of the element which currently has the active class within theCollection."
您可以遍历 div 并检查哪个 div 具有活动的 class。请运行验证码
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>