Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
99
rated 0 times [  102] [ 3]  / answers: 1 / hits: 55579  / 11 Years ago, thu, september 19, 2013, 12:00:00

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>

More From » children

 Answers
6

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


[#75598] Wednesday, September 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darleneh

Total Points: 231
Total Questions: 110
Total Answers: 94

Location: Spain
Member since Thu, Dec 23, 2021
3 Years ago
darleneh questions
;