gpt4 book ai didi

javascript - 获取具有 ID 的父元素的子元素的子元素

转载 作者:数据小太阳 更新时间:2023-10-29 04:25:12 25 4
gpt4 key购买 nike

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

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

最佳答案

非 jQuery 解决方案

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

jQuery 解决方案

使用 :eq 选择器:

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

使用 :nth-child 选择器:

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

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

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

来自 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() Selector

关于javascript - 获取具有 ID 的父元素的子元素的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18890383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com