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;
}