javascript 获取带有 ID 的父元素的子元素的子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18890383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 13:35:45  来源:igfitidea点击:

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

javascriptchildren

提问by Alpotato

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 :(

我需要使用javascript访问id =“part1”的元素的孩子的孩子的孩子。所以基本上,我想到达 span 元素的第三个表的第三行,但我似乎无法让它工作:(

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

回答by letiagoalves

Non-jQuery solution

非 jQuery 解决方案

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

jQuery solution

jQuery 解决方案

Using :eqselector:

使用:eq选择器:

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

Using :nth-childselector:

使用:nth-child选择器:

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

:eqand :nth-childselectors selects all elements that are the nth-child of their parent. However :eqfollows "0-indexed" counting and nth-childfollows "1-indexed".

:eq:nth-child选择器选择作为其父元素的第 n 个子元素的所有元素。然而,:eq遵循“0-indexed”计数并nth-child遵循“1-indexed”。

Be aware that :eqand nth:childselectors work differently. In this case it would do the same because you only have tableelements inside span#part1.

请注意:eqnth:child选择器的工作方式不同。在这种情况下,它会做同样的事情,因为table里面只有元素span#part1

From jQuery documentation:

来自 jQuery 文档:

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.

:nth-child(n) 伪类很容易与 :eq(n) 混淆,即使两者可能导致匹配元素截然不同。使用 :nth-child(n),所有子元素都被计算在内,无论它们是什么,并且指定元素仅在与附加到伪类的选择器匹配时才被选中。使用 :eq(n) 只计算附加到伪类的选择器,不限于任何其他元素的子元素,并且选择第 (n+1) 个(n 是从 0 开始的)。

Reference:

参考:

:nth-child() Selector

:nth-child() 选择器

回答by Praind

try this

试试这个

this.parentNode().getElementsByTagName("table")[2].childNodes[2];

回答by frenchie

I prefer using .find()rather than the sizzle engine. Something like this:

我更喜欢使用.find()而不是嘶嘶声引擎。像这样的东西:

var TheThirdRow = $('#part1').find('table')
                             .eq(2)
                             .find('tr')
                             .eq(2);