You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取指定class元素的索引并忽略其他同级兄弟元素

问题说明

给定HTML结构如下:

<div class="collection">
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
    <div class="item selected"></div>
    <div class="item"></div>
</div>

需要获取所有class包含selected的div元素的索引,计算索引时忽略其他不满足条件的同级兄弟元素,本例预期返回的索引结果为0、1、2,而非默认全同级节点计算得到的1、3、5。

实现方案

核心逻辑:不要直接在全量同级节点范围内计算位置,先把所有符合筛选条件的元素单独筛选出来组成集合,元素在这个筛选集合内的下标就是需要的目标索引。

原生JavaScript实现

直接通过选择器拿到所有符合条件的selected元素,遍历集合时循环自带的下标就是目标索引:

// 选中所有带selected类的item元素
const selectedList = document.querySelectorAll('.collection .item.selected');
// 遍历即可拿到每个元素对应的目标索引
selectedList.forEach((element, index) => {
    console.log('当前元素索引:', index);
    // 依次输出0、1、2,符合预期
});

如果需要单独获取某一个已知selected元素的对应索引,可以把NodeList转为数组后调用indexOf获取:

const targetEl = document.querySelectorAll('.collection .item.selected')[1]; // 取第二个selected元素
const targetIndex = Array.from(selectedList).indexOf(targetEl);
console.log(targetIndex); // 输出1

jQuery实现

注意:无参数调用index()是常见使用误区,该方法默认会把当前元素放到所有同级兄弟节点中计算位置,直接调用会得到1、3、5的错误结果。

正确做法是先拿到筛选后的selected元素集合,在集合范围内计算索引:

const $selectedList = $('.collection .item.selected');
$selectedList.each(function() {
    const currentIndex = $selectedList.index(this);
    console.log(currentIndex); // 依次输出0、1、2
});

内容的提问来源于stack exchange,提问作者DNa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 17:15:45