Javascript 如何选择相同类型的第n个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41848550/
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-08-23 00:41:28  来源:igfitidea点击:

How to select nth element of the same type

javascriptcssdomcss-selectors

提问by tfchen

I would like to select the nth tdfrom all of the td, how do I do that?

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

I know I can do it with document.querySelectorAll("td")[nth], but I'm looking for a pure css way.

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

I tried document.querySelectorAll("td:nth-child(77)"), but it doesn't give the result as document.querySelectorAll("td")[77]does.

我试过document.querySelectorAll("td:nth-child(77)"),但它没有给出结果document.querySelectorAll("td")[77]

采纳答案by BoltClock

I know I can do it with document.querySelectorAll("td")[nth], but I'm looking for a pure css way.

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

There is no pure CSS equivalent. See Matching the first/nth element of a certain type in the entire document

没有纯 CSS 等效项。参见匹配整个文档中某个类型的第一个/第n个元素

回答by Kejt

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>  

UP. Snippet shows that you cannot select TD elements globally, but you can get nth td element in given TR. Is this what you are looking for?

向上。Snippet 显示您不能全局选择 TD 元素,但您可以获得给定 TR 中的第 n 个 td 元素。这是你想要的?

there is selector :nth-of-type(77)

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

should help you.

应该可以帮助你。

nth-childselector counts all children of given element - including other types of tags. Also css selector counts from 1, when JS querySelectorresult arrayfrom 0

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

回答by Armaniimus

There is a pure css way named ==> :nth-of-type
For example to select the 77th td element of each parent in the document the syntax is

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

td:nth-of-type(77)

td:nth-of-type(77)

For more information about the :nth-of-type selector see the Morzilla developer network if these links will break let me know in a comment below.

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

//For the element it self see //
https://developer.mozilla.org/nl/docs/Web/CSS/:nth-of-type

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

//For syntax about all the selections you can make with :nth-child and :nth-of-type see // https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

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