search

Home  >  Q&A  >  body text

javascript - 如何获取getElementsByClassName()数组的下标?

比如,我用getElementsByClassName()获取了5个标签,我又用this控制了其中第二个标签,如何获取this所指向标签在getElementsByClassName()数组中的位置?

ringa_leeringa_lee2913 days ago1264

reply all(2)I'll reply

  • ringa_lee

    ringa_lee2017-04-11 09:59:23

    更正一个错误,getElementsByClassName() 拿到的结果并不是数组,而 HTMLCollection 对象。

    1

    2

    3

    4

    5

    6

    7

    <code class="javascript">const elements = Array.from(document.getElementsByClassName('.class-name'));

     

    // const elements = Array.prototype.slice.apply(document.getElementsByClassName('.class-name'));

     

    const that = elements[3];

     

    console.log(elements.indexOf(that));</code>

    思路是将获取到的 HTMLCollection 对象转换为数组,再使用数组的 indexOf() 方法获取指定元素的索引。

    reply
    0
  • PHP中文网

    PHP中文网2017-04-11 09:59:23

    可以设置this.index

    1

    2

    3

    <code>`for(var i=0;i<elsEments.length;i++){

        elsEments[i].index=i;

    }</code>

    this.index就是这个元素的下标
    `

    reply
    0
  • Cancelreply