Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelectorAll and :first child

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>
like image 428
notforever Avatar asked Jan 17 '17 17:01

notforever


3 Answers

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>
like image 155
Sebastian Simon Avatar answered Oct 19 '22 04:10

Sebastian Simon


In '.wikitable tr:first-child td:first-child a', tr:first-child will select only tr elements that are a first child (i.e. it only selects the first tr).

'.wikitable tr td:first-child a' will go to each row in the '.wikitable' table and select any a anchors in the first cell (presumably there will be only one, but technically there can be more).

like image 28
Harris Avatar answered Oct 19 '22 04:10

Harris


you need to iterate over all the rows so 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>
like image 32
Deep Avatar answered Oct 19 '22 06:10

Deep