Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding DOM node index

Tags:

javascript

dom

People also ask

What is the DOM index?

The DOM option index Property is used to set or return the index position of option value in a dropdown list. The index starts from zero. Syntax: It is used to return the index property.

How do I access DOM nodes?

Accessing Elements by ID The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object.


The shortest possible way, without any frameworks, in all versions of Safari, FireFox, Chrome and IE >= 9:

var i = Array.prototype.indexOf.call(e.childNodes, someChildEl);


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 my examples above in this answer 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.


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

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

A modern native approach might include Array.from(e.children).indexOf(theChild)

No IE support, but Edge works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from