23

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

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

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
tfchen
  • 539
  • 2
  • 6
  • 12

3 Answers3

38

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?

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

should help you.

nth-child selector counts all children of given element - including other types of tags. Also css selector counts from 1, when JS querySelector result array from 0

Kasia
  • 1,665
  • 1
  • 10
  • 16
  • I tried querySelectorAll("td:nth-of-type(77)"), but it returns the result as querySelectorAll("td:nth-child(77)"), just empty list. – tfchen Jan 25 '17 at 10:16
21

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

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

Community
  • 1
  • 1
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
2

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

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.

//For the element it self see //
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

Armaniimus
  • 57
  • 3
  • 2
    For the purposes of links not working for future readers try to post some code examples in your answer – JoeMoe1984 Oct 11 '17 at 21:55
  • This is wrong. The documentation says "nth number of child of its parent element", so you're only getting the nth in a given parent, not the whole document. – Ehsan Kia Jun 14 '19 at 19:34
  • @Ehsan Kia I've updated the answer to be more exact in it's explaination. – Armaniimus Jun 15 '19 at 22:26