Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select nth element of the same type

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.

like image 834
tfchen Avatar asked Jan 25 '17 10:01

tfchen


1 Answers

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

like image 180
Kasia Avatar answered Sep 21 '22 15:09

Kasia