110

I need to find an index of element inside its container by object reference. Strangely, I cannot find an easy way. No jQuery please - only DOM.

UL
 LI
 LI
 LI - my index is 2
 LI

Yes, I could assign IDs to each element and loop through all nodes to match the ID but it seems a bad solution. Isn't there something nicer?

So, say I have an object reference to the third LI as in the example above. How do I know it is index 2?

Thanks.

4
  • How do you need to get the index? hover.. etc ??
    – Clyde Lobo
    Commented Aug 1, 2012 at 15:03
  • 1
    why not perform a previousSibling on the li reference until you hit null? Commented Aug 1, 2012 at 15:04
  • possible duplicate of Finding DOM node index Commented Dec 8, 2014 at 4:40
  • I think it would be easy if you add custom attribute to the li element. For example, <li index="0">, <li index="1"> and you can access it easily. Commented Nov 14, 2015 at 18:33

13 Answers 13

120

You could make usage of Array.prototype.indexOf. For that, we need to somewhat "cast" the HTMLNodeCollection into a true Array. For instance:

var nodes = Array.prototype.slice.call( document.getElementById('list').children );

Then we could just call:

nodes.indexOf( liNodeReference );

Example:

var nodes = Array.prototype.slice.call( document.getElementById('list').children ),
    liRef = document.getElementsByClassName('match')[0];

console.log( nodes.indexOf( liRef ) );
<ul id="list">
    <li>foo</li>
    <li class="match">bar</li>
    <li>baz</li>    
</ul>

5
  • 4
    Note: .childNodes and .children are different things. .children is a subset, a list of all ElementNodes only.
    – Ian Clark
    Commented Jun 20, 2014 at 8:43
  • 3
    The previousElementSibling solution is better because it will exclude text nodes and will return the index of the element that you expect. Commented Dec 8, 2014 at 6:53
  • 5
    ES6 syntax: const index = [...el.parentNode.children].indexOf(el)
    – ESR
    Commented Jul 12, 2018 at 12:58
  • 4
    I'd actually much prefer Array.from( el.parentNode.children ).indexOf( el ); on that instance, just for readability.
    – jAndy
    Commented Jul 13, 2018 at 17:25
  • Array.prototype.indexOf.call(nodes, node) works for me.
    – Tavin
    Commented Jul 10, 2023 at 22:59
99

Here is how I do (2018 version ?) :

const index = [...el.parentElement.children].indexOf(el);

Tadaaaam. And, if ever you want to consider raw text nodes too, you can do this instead :

const index = [...el.parentElement.childNodes].indexOf(el);

I spread the children into an array as they are an HTMLCollection (thus they do not work with indexOf).

Be careful that you are using Babel or that browser coverage is sufficient for what you need to achieve (thinkings about the spread operator which is basically an Array.from behind the scene).

5
  • 2
    Really cool! Just added Array.from to the childNodes respectively const index = [...Array.from(el.parentElement.children)].indexOf(el); Commented Jan 29, 2020 at 16:01
  • 2
    If used as part of an interview - you should mention that Array.from ( or [...] ) will create a shallow copy of the collection - whilst Array.prototype.indexOf.call wont.
    – CWright
    Commented Aug 31, 2020 at 11:33
  • 3
    when using [...el.parentElement.children], with typescript, raises the error: Type 'HTMLCollection' is not an array type or does not have a '[Symbol.iterator]()' method that returns an iterator. in this case better this approach: Array.from(el.parentElement.children)
    – darkziul
    Commented Feb 2, 2021 at 13:29
  • It seems this method will have all children into the array, that is to say all siblings of el, but this is not always intended and this method doesn't allow to exclude siblings from the array. For instance el = document.querySelectorAll('div:not(.exclude)')
    – Max
    Commented Aug 26, 2021 at 21:12
  • 2
    @DavidDalBusco, you're creating 2 arrays. If you're using Array.from then just Array.from(el.parentElement.children).indexOf(el) is sufficient. No need to create an array and then spread that array into yet another array. Also, while [...children] is terse, it is creating a temporary array just for the purpose of searching it and then discarding the temporary. If you want speed then Array.prototype.indexOf.call(el.parentElement.children, el) should be faster as no temporary array is created. Speed isn't always important and I'd chose [...children] most of the time.
    – gman
    Commented Jun 8, 2022 at 18:35
54

2017 update

The original answer below assumes that the OP wants to include non-empty text node and other node types as well as elements. It doesn't seem clear to me now from the question whether this is a valid assumption.

Assuming instead you just want the element index, previousElementSibling is now well-supported (which was not the case in 2012) and is the obvious choice now. The following (which is the same as some other answers here) will work in everything major except IE <= 8.

function getElementIndex(node) {
    var index = 0;
    while ( (node = node.previousElementSibling) ) {
        index++;
    }
    return index;
}

Original answer

Just use previousSibling until you hit null. I'm assuming you want to ignore white space-only text nodes; if you want to filter other nodes then adjust accordingly.

function getNodeIndex(node) {
    var index = 0;
    while ( (node = node.previousSibling) ) {
        if (node.nodeType != 3 || !/^\s*$/.test(node.data)) {
            index++;
        }
    }
    return index;
}
12
  • 6
    +1 This is fastest compared to any other method described here. For newer browser, previousElementSibling can be used without these two conditions.
    – Akash Kava
    Commented Nov 12, 2013 at 12:07
  • @bjb568: Is your point that there is a set of unnecessary parentheses?
    – Tim Down
    Commented Mar 19, 2014 at 9:10
  • 2
    Not unnecessary. It's not enough. Everyone knows that you need at least another 7 for beauty.
    – bjb568
    Commented Mar 19, 2014 at 16:07
  • @bjb568: Probably best to close them as well.
    – Tim Down
    Commented Mar 19, 2014 at 16:25
  • 3
    what does this !/^\s*$/.test(node.data) do exactly?
    – maxlego
    Commented Feb 27, 2016 at 19:59
27
Array.prototype.indexOf.call(this.parentElement.children, this);

Or use let statement.

3
  • @citykid, sure, it's more terse but it's silly to create a temporary array just to access a function of that array.
    – gman
    Commented Oct 12, 2020 at 13:25
  • @gman The indexOf method does not create a temporary array, unlike many other answers (.slice(), .from(), array spread etc.). If you look at the spec, it will directly iterate on the children list as if it is an array, so it is fast.
    – Sheepy
    Commented Jun 8, 2022 at 15:52
  • @Sheepy, the comment I was responding to has been deleted. The comment has nothing to do with the answer by Alexander, it has to do with a comment by citykid that suggested [].indexOf.call(this.parametElement.children, this). That does create a temporary array.
    – gman
    Commented Jun 8, 2022 at 18:13
10

You can use this to find the index of an element:

Array.prototype.indexOf.call(yourUl, yourLi)

This for example logs all indices:

var lis = yourList.getElementsByTagName('li');
for(var i = 0; i < lis.length; i++) {
    console.log(Array.prototype.indexOf.call(lis, lis[i]));
}​

JSFIDDLE

2
  • I misinterpreted the question. Edited!
    – user657496
    Commented Aug 1, 2012 at 15:02
  • The previousElementSibling solution is better because it will exclude text nodes and will return the index of the element that you expect. Commented Dec 8, 2014 at 6:53
10

For just elements this can be used to find the index of an element amongst it's sibling elements:

function getElIndex(el) {
    for (var i = 0; el = el.previousElementSibling; i++);
    return i;
}

Note that previousElementSibling isn't supported in IE<9.

2
  • 1
    What if it will not be a previous sibling but next? Commented Jul 12, 2016 at 11:03
  • 2
    @RooticalV.: Not sure what you mean. Did you meant to ask what happens if there is no previous sibling? In that case the loop will automatically exit, since the value of the expression "el = el.previousElementSibling" will be false (as it is null). Or did you meant to ask what would happen if you replaced "previousElementSibling" by "nextElementSibling" in the above code? Well, in that case the loop would count the number of siblings still following the element.
    – HammerNL
    Commented Oct 11, 2016 at 8:50
8

A modern native approach could make use of 'Array.from()' - for example:

const el = document.getElementById('get-this-index')
const index = Array.from(document.querySelectorAll('li')).indexOf(el)
document.querySelector('h2').textContent = `index = ${index}`
<ul>
  <li>zero
  <li>one
  <li id='get-this-index'>two
  <li>three
</ul>
<h2></h2>

5
    const nodes = Array.prototype.slice.call( el.parentNode.childNodes );
    const index = nodes.indexOf(el);
    console.log('index = ', index);
1
  • you could also do Array.fom instead of Array.prototype.slice.call but the same result Commented Dec 24, 2022 at 5:32
2

An example of making an array from HTMLCollection

<ul id="myList">
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

<script>
var tagList = [];

var ulList = document.getElementById("myList");

var tags   = ulList.getElementsByTagName("li");

//Dump elements into Array
while( tagList.length != tags.length){
    tagList.push(tags[tagList.length])
};

tagList.forEach(function(item){
        item.addEventListener("click", function (event){ 
            console.log(tagList.indexOf( event.target || event.srcElement));
        });
}); 
</script>
1

If you want to write this compactly all you need is:

var i = 0;
for (;yourElement.parentNode[i]!==yourElement;i++){}
indexOfYourElement = i;

We just cycle through the elements in the parent node, stopping when we find your element.

You can also easily do:

for (;yourElement.parentNode.getElementsByTagName("li")[i]!==yourElement;i++){}

if that's all you want to look through.

1

You can iterate through the <li>s in the <ul> and stop when you find the right one.

function getIndex(li) {
    var lis = li.parentNode.getElementsByTagName('li');
    for (var i = 0, len = lis.length; i < len; i++) {
        if (li === lis[i]) {
            return i;
        }
    }

}

Demo

0

Another example just using a basic loop and index check

HTML

<ul id="foo">
    <li>0</li>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

JavaScript runs onload/ready or after ul is rendered

var list = document.getElementById("foo"),
    items = list.getElementsByTagName("li");

list.onclick = function(e) {
    var evt = e || window.event,
    src = evt.target || evt.srcElement;
    var myIndex = findIndex(src);
    alert(myIndex);
};

function findIndex( elem ) {
    var i, len = items.length;
    for(i=0; i<len; i++) {
        if (items[i]===elem) {
            return i;
        }
    }
    return -1;
}

Running Example

jsFiddle

0

Just pass the object reference to the following function and you will get the index

function thisindex(elm) 
{ 
    var the_li = elm; 
    var the_ul = elm.parentNode; 
    var li_list = the_ul.childNodes; 

    var count = 0; // Tracks the index of LI nodes

    // Step through all the child nodes of the UL
    for( var i = 0; i < li_list.length; i++ )
    {
        var node = li_list.item(i);
        if( node )
        {
        // Check to see if the node is a LI
            if( node.nodeName == "LI" )
            {
            // Increment the count of LI nodes
                count++;
            // Check to see if this node is the one passed in
                if( the_li == node )
                {
                    // If so, alert the current count
                    alert(count-1);
                }
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.