querySelectorAll and :first child

notforever picture notforever · Jan 17, 2017 · Viewed 11.7k times · Source

I'm trying to get a list of only the first links per row in one wikipedia table with querySelectorAll but I am not sure why the :first-child selector is not working. I know there is other ways to do it but I want to know if there is a solution to this specific problem with the querySelectorAll function.

see my attemps below the html:

<table class='wikitable'>
  <tr>
    <td>
      <a href="" title="">John doe</a>
    </td>
    <td>
      <a href="" title="">other link</a>
    </td>
    </tr>

  <tr>
    <td>
      <a href="" title="">Mary Jane</a>
    </td>
    <td>
      <a href="" title="">another link</a>
    </td>
  </tr>
</table>

My Code:

let list = document.querySelectorAll(('.wikitable tr:first-child td:first-child a')); 

the previous code is just returning a node with one element:

<a href="" title="">John doe</a>

Instead a list:

<a href="" title="">John doe</a>
<a href="" title="">Mary Jane</a>

Answer

Sebastian Simon picture Sebastian Simon · Jan 17, 2017

The correct selector should be

".wikitable tr td:first-child a"

tr:first-child means “the tr which is the first child”. This only applies to

<tr>
  <td>
    <a href="" title="">John doe</a>
  </td>
  <td>
    <a href="" title="">other link</a>
  </td>
</tr>