Search code examples
javascriptchildren

Getting child element of a child element of a parent with ID


I need to get to the child of the child of the child of an element with an id = "part1" with javascript. So essentially, I want to get to the 3rd row of the 3rd table of the span element but I can't seem to get it to work :(

<span id = "part1">
<table> </table>
<table> </table>
<table>
    <tr> ... </tr> 
    <tr> ... </tr> 
    <tr> ... </tr> (get this row)
</table>
</span>

Solution

  • Non-jQuery solution

    var span = document.getElementById('part1');
    var row = span.getElementsByTagName('table')[2].childNodes[2];
    

    jQuery solution

    Using :eq selector:

    var $row = $('#part1 > table:eq(2) > tr:eq(2)');
    

    Using :nth-child selector:

    var $row = $('#part1 > table:nth-child(3) > tr:nth-child(3)');
    

    :eq and :nth-child selectors selects all elements that are the nth-child of their parent. However :eq follows "0-indexed" counting and nth-child follows "1-indexed".

    Be aware that :eq and nth:child selectors work differently. In this case it would do the same because you only have table elements inside span#part1.

    From jQuery documentation:

    The :nth-child(n) pseudo-class is easily confused with :eq(n), even though the two can result in dramatically different matched elements. With :nth-child(n), all children are counted, regardless of what they are, and the specified element is selected only if it matches the selector attached to the pseudo-class. With :eq(n) only the selector attached to the pseudo-class is counted, not limited to children of any other element, and the (n+1)th one (n is 0-based) is selected.

    Reference:

    :nth-child() Selector