Steve Lloyd
Steve Lloyd

Reputation: 949

Get a node's index

Given any arbitrary node in the DOM, is it possible to get the Node's index so that I can use it in nth-child? I have tried the following without success

function getNodeIndex(node){
    if(undefined == node){return undefined;}
    if(undefined == node.parentNode){return undefined;}
    if(undefined == node.parentNode.childNodes){return undefined;}
    for (var i=0;i<node.parentNode.childNodes.length;i++){
        if(node.parentNode.childNodes[i]==node){return i;}
    }
    return undefined;
}

Upvotes: 0

Views: 40

Answers (1)

adeneo
adeneo

Reputation: 318182

Your function seems to return some strange results, mostly because it also counts textNodes, comments and everything else, not just the elements.

I'd do it like this, counting up through sibling elements and making it zero based

function getNodeIndex(elem) {
    if (elem && elem.parentNode) {
        var i = 0;
        while( elem.previousElementSibling ) {
            i++;
            elem = elem.previousElementSibling;
        }
        return i;
    }
    return -1;
}

Upvotes: 2

Related Questions