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>
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>
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).
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With