无论深度如何,如何获取根子元素的当前索引

斯塔克里托

我有一个container有几个孩子div divs每个孩子divs都有未知的结构和内容。某处有一些按钮应该只返回被点击的根子节点的当前索引。(不使用唯一 ID)

例子:

<div class="conatainer">
    <div class="rootChild">
        <button> Get rootChild index </button>  // should return 0
    </div>

    <div class="rootChild">
        <div class="someDiv">
            <p> Some text here </p>
            <button> Get rootChild index </button> // should return 1
        </div>
    </div>

    <div class="rootChild">
        <div class="someOtherDiv">
            <div class="andAnotherDiv">
                <button> Get rootChild index </button> // should return 2
            </div>
        </div>
    </div>
</div> 
查理特

您可以从子类中创建一个数组,并从按钮查找到子类最近的元素,并用于indexOf()获取该子类在数组中的索引

const cont = document.querySelector('.conatainer'),
  children = Array.from(cont.children);

cont.addEventListener('click', e => {
  if (e.target.matches('.rootChild button')) {    
    const idx = children.indexOf( e.target.closest('.rootChild'))
    console.log('Index =', idx)
  }
})
<div class="conatainer">
  <div class="rootChild">
    <button> Get rootChild index </button> // should return 0
  </div>

  <div class="rootChild">
    <div class="someDiv">
      <p> Some text here </p>
      <button> Get rootChild index </button> // should return 1
    </div>
  </div>

  <div class="rootChild">
    <div class="someOtherDiv">
      <div class="andAnotherDiv">
        <button> Get rootChild index </button> // should return 2
      </div>
    </div>
  </div>
</div>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章