【问题标题】:How to select nth element of the same type如何选择相同类型的第n个元素
【发布时间】:2017-06-10 10:53:33
【问题描述】:

我想从所有td 中选择第n 个td,我该怎么做?

我知道我可以用 document.querySelectorAll("td")[nth] 做到这一点,但我正在寻找一种纯 css 方式。

我尝试了document.querySelectorAll("td:nth-child(77)"),但它没有像document.querySelectorAll("td")[77] 那样给出结果。

【问题讨论】:

    标签: javascript css dom css-selectors


    【解决方案1】:

    var result = document.querySelectorAll("table td:nth-of-type(2)");
    
    console.log(result);
    <table>
      <tr><td>nope</td><td>nope</td></tr>
      <tr><td>nope</td><td>here</td></tr>
      
    </table>  

    向上。片段显示您无法全局选择 TD 元素,但您可以获得给定 TR 中的第 n 个 td 元素。这是你要找的吗?

    有选择器:nth-of-type(77)

    应该能帮到你。

    nth-child 选择器计算给定元素的所有子元素 - 包括其他类型的标签。当 JS querySelector 结果 array 从 0 时,css 选择器也从 1 开始计数

    【讨论】:

    • 我尝试了 querySelectorAll("td:nth-of-type(77)"),但它返回结果为 querySelectorAll("td:nth-child(77)"),只是空列表。
    【解决方案2】:

    我知道我可以用 document.querySelectorAll("td")[nth] 做到这一点,但我正在寻找一种纯 css 方式。

    没有纯 CSS 等价物。见Matching the first/nth element of a certain type in the entire document

    【讨论】:

      【解决方案3】:

      有一种纯 css 方式,名为 ==> :nth-of-type
      例如,要选择文档中每个父级的第 77 个 td 元素,语法为

      td:nth-of-type(77)

      有关 :nth-of-type 选择器的更多信息,请参阅 Morzilla 开发人员网络,如果这些链接会损坏,请在下面的评论中告诉我。

      //对于它自己的元素看 //
      https://developer.mozilla.org/nl/docs/Web/CSS/:nth-of-type

      //有关您可以使用 :nth-child 和 :nth-of-type 进行的所有选择的语法,请参见 // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

      【讨论】:

      • 为了链接不适用于未来的读者,请尝试在您的答案中发布一些代码示例
      • 这是错误的。文档说“其父元素的第 n 个子元素”,因此您只能获得给定父元素中的第 n 个,而不是整个文档。
      • @Ehsan Kia 我已经更新了答案,使其解释更加准确。
      猜你喜欢
      • 1970-01-01
      • 2013-12-13
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 2015-05-30
      • 2013-01-25
      相关资源
      最近更新 更多