I am trying to get the index of child of its parent. For example:-
<div> <table> <tr id="rahul"> <td> Hi this is ABC </td> <td> Hi this is XYZ </td> </tr> </table> </div> And my java script code is:-
<script> $(document).ready(function() { document.onmousedown = mouseDown; function mouseDown(e) { var element = document.elementFromPoint(e.clientX,e.clientY); console.log("Clicked element is:" + element.tagName); var i=1; while (element.nextSibling != null) { element = element.nextSibling; console.log('Sibling No:' + (i++) + " " + element.tagName); } } }); </script> When i click on "Hi this is ABC" according to me, it should print
Sibling No.1 TD But actually It is printing
Clicked element is:TD jsoupTest.html:10 Sibling No:1 undefined jsoupTest.html:14 Sibling No:2 TD jsoupTest.html:14 Sibling No:3 undefined It arises a doubt why this is printing undefined as sibling of TD? And my idea is to find the no of siblings clicked element has and i can find out the total no of children its parent has. So now I can find the index of clicked element by subtracting no of siblings from total children of its parent.
Please tell me if there is any better alternative to get this.
$(document).ready(...)), I've added the jQuery tag to your question -- as it will affect the answers pretty markedly. (E.g.: This is one line with jQuery, multiple lines without.)undefinedbecause between thetdelement nodes (and after the last one), there is a text node (containing the white space characters) and text nodes don't have a tag name. Useelement.nodeNameinstead and you will see.var i = 0.