所以我们在页面中有一个li列表
<li class="page-list">
<ol>
<li><button data-ember-action="" data-ember-action-2354="2354">2</button></li>
<li><button data-ember-action="" data-ember-action-2356="2356">3</button></li>
<li><button data-ember-action="" data-ember-action-2358="2358">4</button></li>
<li><button data-ember-action="" data-ember-action-2360="2360">5</button></li>
<li><button data-ember-action="" data-ember-action-2362="2362">6</button></li>
<li class="active">7</li>
<li><button data-ember-action="" data-ember-action-2364="2364">8</button></li>
<li><button data-ember-action="" data-ember-action-2366="2366">9</button></li>
<li><button data-ember-action="" data-ember-action-2368="2368">10</button></li>
<li><button data-ember-action="" data-ember-action-2370="2370">11</button></li>
</ol>
</li>
现在,我知道如何找到<li class="page-list">
内所有li的长度,但是如何确定特定li在列表中的位置?
例如,在上面的粘贴代码中,有一个<li>
故意未对齐。现在,我想从给定的li列表中确定其位置,如何使用javascript(如果您算一下,它在数组中的第5个)就可以做到这一点
答案 0 :(得分:3)
将元素的parentNode转换为数组,然后找到其自己的索引:
const el = document.querySelector("li.active");
const elPosition = [...el.parentNode.children].indexOf(el);
答案 1 :(得分:1)
假设您不想使用jQuery ...
document.querySelector("li.page-list").querySelectorAll("ol li").forEach(function (listItem, index) {
if (listItem.classList.contains("active"))
console.log(`And the winner is #${index}!`)
});
<li class="page-list">
<ol>
<li><button data-ember-action="" data-ember-action-2354="2354">2</button></li>
<li><button data-ember-action="" data-ember-action-2356="2356">3</button></li>
<li><button data-ember-action="" data-ember-action-2358="2358">4</button></li>
<li><button data-ember-action="" data-ember-action-2360="2360">5</button></li>
<li><button data-ember-action="" data-ember-action-2362="2362">6</button></li>
<li class="active">7</li>
<li><button data-ember-action="" data-ember-action-2364="2364">8</button></li>
<li><button data-ember-action="" data-ember-action-2366="2366">9</button></li>
<li><button data-ember-action="" data-ember-action-2368="2368">10</button></li>
<li><button data-ember-action="" data-ember-action-2370="2370">11</button></li>
</ol>
</li>