Is it possible to get element's numerical index in its parent node without looping?

前端 未结 7 1236
攒了一身酷
攒了一身酷 2020-11-30 07:21

Normally I\'m doing it this way:

for(i=0;i
相关标签:
7条回答
  • 2020-11-30 08:06

    Option #1

    You can use the Array.from() method to convert an HTMLCollection of elements to an array. From there, you can use the native .indexOf() method in order to get the index:

    function getElementIndex (element) {
      return Array.from(element.parentNode.children).indexOf(element);
    }
    

    If you want the node index (as oppose to the element's index), then replace the children property with the childNodes property:

    function getNodeIndex (element) {
      return Array.from(element.parentNode.childNodes).indexOf(element);
    }
    

    Option #2

    You can use the .call() method to invoke the array type's native .indexOf() method. This is how the .index() method is implemented in jQuery if you look at the source code.

    function getElementIndex(element) {
      return [].indexOf.call(element.parentNode.children, element);
    }
    

    Likewise, using the childNodes property in place of the children property:

    function getNodeIndex (element) {
      return [].indexOf.call(element.parentNode.childNodes, element);
    }
    

    Option #3

    You can also use the spread operator:

    function getElementIndex (element) {
      return [...element.parentNode.children].indexOf(element);
    }
    
    function getNodeIndex (element) {
      return [...element.parentNode.childNodes].indexOf(element);
    }
    
    0 讨论(0)
提交回复
热议问题