jQuery index() in vanilla javascript

前端 未结 5 1612
北荒
北荒 2020-12-01 12:16

As per the jQuery api, the complementary operation to .get(), which accepts an index and returns a DOM node, .index() can take a DOM node and returns an index.

5条回答
  •  既然无缘
    2020-12-01 12:56

    I've modified Travis J answer to not include TextNodes and made a function out of it.

    You can run it in the console and see (on stackoverflow).

    Classic way:

    function getNodeindex( elm ){ 
        var c = elm.parentNode.children, i = 0;
        for(; i < c.length; i++ )
            if( c[i] == elm ) return i;
    }
    
    // try it
    var el = document.getElementById("sidebar");
    getNodeindex(el);
    

    With ES2015:

    function getNodeindex( elm ){ 
        return [...elm.parentNode.children].findIndex(c => c == elm)
        // or
        return [...elm.parentNode.children].indexOf(elm)
    }
    

    Demo:

    const getNodeindex = elm => [...elm.parentNode.children].indexOf(elm)
    
    
    


    I also want to point to another thread on the same matter, which has a great answer (for people seeking older IE support)

提交回复
热议问题