views:

1831

answers:

5

I want find the index of a given DOM node. It's like the inverse of doing

document.getElementById('id_of_element').childNodes[K]

I want to instead extract the value of K given that I already have the reference to the child node and the parent node. How do I do this?

A: 

I think the only way to do this is to loop through the parent's children until you find yourself.

var K = -1;
for (var i = myNode.parent.childNodes.length; i >= 0; i--)
{
    if (myNode.parent.childNodes[i] === myNode)
    {
        K = i;
        break;
    }
}

if (K == -1)
    alert('Not found?!');
Greg
+2  A: 

RoBorg's answer works... or you could try...

var k = 0;
while(elem.previousSibling){
    k++;
    elem = elem.previousSibling;
}
alert('I am at index: ' + k);
scunliffe
A: 

Thank you to both of you! Works great! :) :) :)

+4  A: 

A little shorter, expects the element to be in elem, returns k.

for (var k=0,e=elem; e = e.previousSibling; ++k);

After a comment from Justin Dearing I reviewed my answer and added the following:

Or if you prefer "while":

var k=0, e=elem;
while (e = e.previousSibling) { ++k;}

The original question was how to find the index of an existing DOM element. Both of the examples above expects elem to be an DOM element and that the element still exists in the DOM. They will fail if you give them an null object or an object that don't have previousSibling. A more fool-proof way would be something like this:

var k=-1, e=elem;
while (e) {
    if ( "previousSibling" in e ) {
        e = e.previousSibling;
        k = k + 1;
    } else {
        k= -1;
        break;
    }
}

If e is null or if previousSibling is missing in one of the objects, k is -1.

some
@scunliffe. Thank you!
some
@some, I had to modify the example, and it looks like you have to move e = e.previousSibling to the miffle of the for loop and do a null check in firefox 3.5.
Justin Dearing
@Justin: "e=e.previousSibling" is in the middle... The for-loop declares k=0 and e=elem. Then it execute e=e.previousSibling until e===null. For every successful loop it increments k by one. And it works in FF3.5.2. Please explain what you think is wrong.
some
@Justin: Added some more examples.
some
A: 

using a framework like prototype you could use this :

$(el).up().childElements().indexOf($(el))
lezardo