首页 > 解决方案 > 获取 div 中存在的元素的索引?

问题描述

<div id="div">
    <h1 id="1">Index 1</h1>
    <h1 id="2">Index 2</h1>
    <h1 id="3">Index 3</h1>
</div>
// Something like this, but this doesn't work.
const div = document.getElementById('div').childNodes;
const _h1 = document.getElementById('2');
for (const i of div) {
    if (i == _h1) {
        console.log(div.indexOf(i);
    }
}

我有一个div有一些子节点的。我也有一个元素_h1_h1假设我们div不知道div.

非常感谢任何帮助。

谢谢

标签: javascripthtmlindexof

解决方案


推荐阅读