Finding distance between two elements

Finding distance between two elements

Hi,

I'm at my wit's end now, though it's not jQuery issue I venture to post it here for thoughts.
And here's the description.

...
<table id="beforeG1"> ... </table>

<table id="G1"> 
... tons of elements etc. 

<tr> <td id="g11" onclick="findDepth();"></td> </tr>

</table>


function findDepth() {

// find distance between G1 click to add g11 and the element before G1
/* there could be multiple SAME 'G1' id and multiple SAME 'g11' id */
// var node = document.getElementById('g11'), //g11[0], 
var node = document.getElementById('g11'),
depth = 0;
while (node.id != 'beforeG1') {
node = node.previousSibling;  //previousElementSibling; // node.parentNode;
depth++;
}
console.log ('distance:', depth);

}


And please note, I can find distance between g11 and G1 but for the distance between g11 and beforeG1 it generates the infamous "Cannot read property 'id' of undefined" error.

Thanks.