jQuery index() in vanilla javascript
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 = c.length;
while(i--)
if( c[i] == elm )
return i
}
With ES2015:
const getNodeindex = elm => [...elm.parentNode.children].findIndex(c => c == elm)
// or
const getNodeindex = elm => [...elm.parentNode.children].indexOf(elm)
Demo:
const getNodeindex = elm => [...elm.parentNode.children].indexOf(elm)
<button onclick="console.log( getNodeindex(this) )">get index</button>
<button onclick="console.log( getNodeindex(this) )">get index</button>
<button onclick="console.log( getNodeindex(this) )">get index</button>
I also want to point to another thread on the same matter, which has a great answer (for people seeking older IE support)
You can build your own function :
function indexInParent(node) {
var children = node.parentNode.childNodes;
var num = 0;
for (var i=0; i<children.length; i++) {
if (children[i]==node) return num;
if (children[i].nodeType==1) num++;
}
return -1;
}
Demonstration (open the console)