QuerySelectorAll and: first child

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

see my attemps below 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 is:

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

the previous code just returns a node with one element:

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

Instead of a list:

<a href="" title="">John doe</a>
<a href="" title="">Mary Jane</a>
+4
source share
3 answers

The correct selector must be

".wikitable tr td:first-child a"

tr:first-childmeans "the trwho 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>
+4
source

'.wikitable tr:first-child td:first-child a', tr:first-child tr, (.. tr).

'.wikitable tr td:first-child a' ".wikitable" a (, , ).

+4

you need to iterate over all the lines, so the selector will be

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

using tr: first-child will only select the first row.

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

console.log(list);
<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>
Run code
+1
source

Source: https://habr.com/ru/post/1667037/


All Articles