How to get the index of the element in javascript?

后端 未结 5 729
北海茫月
北海茫月 2021-02-07 15:09

The NodeList don\'t have a indexOf(element) method? So, how can I get the element index?

相关标签:
5条回答
  • 2021-02-07 15:24

    Let us say you have the following line:

    const list=document.querySelectAll('.some_class .someother_class');
    

    list will be a nodelist. So we can convert the nodelist to an array and create a new array of indexes as follows:

    const indexArr= [...list].map( element => return [...list].indexOf(element) );
    

    indexArr contains all the indexes of elements in the original list.

    0 讨论(0)
  • 2021-02-07 15:25

    By iterating over the elements, and checking if it matches.

    Generic code that finds the index of the element within it's parents childNodes collection.

    function index(el) {
        var children = el.parentNode.childNodes,
            i = 0;
        for (; i < children.length; i++) {
            if (children[i] == el) {
                return i;
            }
        }
        return -1;
    }
    

    Usage:

    // should return 4
    var idx = index(document.body.childNodes[4]);
    

    EDIT: I can't delete an accepted answer, but @kennebec's answer below is much better, which I'll quote verbatim:

    You can use Array.prototype.indexOf.call() like this

    let nodes = document.getElementsByTagName('*');
    Array.prototype.indexOf.call(nodes, document.body);
    
    0 讨论(0)
  • 2021-02-07 15:35

    You can use Array.prototype.indexOf.call() like this

    let nodes = document.getElementsByTagName('*');
    Array.prototype.indexOf.call(nodes, document.body);
    
    0 讨论(0)
  • 2021-02-07 15:40

    Just add one line in your script:

    NodeList.prototype.indexOf = Array.prototype.indexOf;   // for IE11
    

    Then use indexOf as usual:

    var index = NodeList.indexOf(NodeElement);
    
    0 讨论(0)
  • 2021-02-07 15:43

    The NodeList objet is an Array-like object. So it's possible to "convert" it into an Array using Array.prototype.slice.call()

    var arr = Array.prototype.slice.call(yourNodeListObject); // Now it's an Array.
    arr.indexOf(element); // The index of your element :)
    

    On browsers that support ES6 you can also do this with Array.from()

    const arr = Array.from(yourNodeListObject);
    

    or using the spread operator ...

    const arr = [...yourNodeListObject];
    
    0 讨论(0)
提交回复
热议问题