I added two tests to the jsPerf test. Both use previousElementSibling
, but the second includes compatibility code for IE8 and lower.
Both of them perform extremely well in modern browsers (which is most browsers in use today), but will take a small hit in older browsers.
Here's the first one that doesn't include the compatibility fix. It'll work in IE9 and higher, as well as pretty much all of Firefox, Chrome and Safari.
function findRow6(node) {
var i = 1;
while (node = node.previousElementSibling)
++i;
return i;
}
Here's the version with the compatibility fix.
function findRow7(node) {
var i = 1,
prev;
while (true)
if (prev = node.previousElementSibling) {
node = prev;
++i;
} else if (node = node.previousSibling) {
if (node.nodeType === 1) {
++i;
}
} else break;
return i;
}
Because it automatically grabs element siblings, there's no test needed for nodeType
, and the loop is shorter overall. This explains the large performance increase.
I also added one last version that loops the .children
, and compares the node
to each one.
This isn't quite as fast as the previousElementSibling
versions, but is still faster than the others (at least in Firefox).
function findRow8(node) {
var children = node.parentNode.children,
i = 0,
len = children.length;
for( ; i < len && children[i] !== node; i++)
; // <-- empty statement
return i === len ? -1 : i;
}
Going back to the previousElementSibling
version, here's a tweak that may bump up the performance just a bit.
function findRow9(node) {
var i = 1,
prev = node.previousElementSibling;
if (prev) {
do ++i;
while (prev = prev.previousElementSibling);
} else {
while (node = node.previousSibling) {
if (node.nodeType === 1) {
++i;
}
}
}
return i;
}
I haven't tested it in the jsPerf, but breaking it out into two different loops based on the presence of a previouselementSibling
would only help I would think.
Maybe I'll add it in a bit.
I went ahead and added it to the test linked at the top of this answer. It does help a little bit, so I think it's probably worth doing.
index
position of the node? Also, your code is a little messed up. You should have.nodeType === 1
instead of.nodeType !== 1
.