How to get the index of the element in javascript?

后端 未结 5 732
北海茫月
北海茫月 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: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);
    

提交回复
热议问题