querySelectorAll 和 :first child
querySelectorAll and :first child
我正在尝试使用 querySelectorAll 获取一个维基百科 table 中每行第一个链接的列表,但我不确定为什么 :first-child 选择器不起作用。我知道还有其他方法可以做到这一点,但我想知道 querySelectorAll 函数是否可以解决这个特定问题。
在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>
我的代码:
let list = document.querySelectorAll(('.wikitable tr:first-child td:first-child a'));
前面的代码只是返回一个只有一个元素的节点:
<a href="" title="">John doe</a>
改为列表:
<a href="" title="">John doe</a>
<a href="" title="">Mary Jane</a>
您需要遍历所有行,因此select或将
document.querySelectorAll(('.wikitable tr td:first-child a'));
使用 tr:first-child 只会 select 第一行。
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>
在 '.wikitable tr:first-child td:first-child a'
中,tr:first-child
将 select 只有 tr
个元素是第一个子元素(即只有 select 第一个 tr
).
'.wikitable tr td:first-child a'
将转到“.wikitable”中的每一行 table 和 select 第一个单元格中的任何 a
锚点(大概只有一个,但从技术上讲可以有更多)。
正确的选择器应该是
".wikitable tr td:first-child a"
tr:first-child
表示“tr
即 第一个 child”。这仅适用于
<tr>
<td>
<a href="" title="">John doe</a>
</td>
<td>
<a href="" title="">other link</a>
</td>
</tr>
我正在尝试使用 querySelectorAll 获取一个维基百科 table 中每行第一个链接的列表,但我不确定为什么 :first-child 选择器不起作用。我知道还有其他方法可以做到这一点,但我想知道 querySelectorAll 函数是否可以解决这个特定问题。
在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>
我的代码:
let list = document.querySelectorAll(('.wikitable tr:first-child td:first-child a'));
前面的代码只是返回一个只有一个元素的节点:
<a href="" title="">John doe</a>
改为列表:
<a href="" title="">John doe</a>
<a href="" title="">Mary Jane</a>
您需要遍历所有行,因此select或将
document.querySelectorAll(('.wikitable tr td:first-child a'));
使用 tr:first-child 只会 select 第一行。
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>
在 '.wikitable tr:first-child td:first-child a'
中,tr:first-child
将 select 只有 tr
个元素是第一个子元素(即只有 select 第一个 tr
).
'.wikitable tr td:first-child a'
将转到“.wikitable”中的每一行 table 和 select 第一个单元格中的任何 a
锚点(大概只有一个,但从技术上讲可以有更多)。
正确的选择器应该是
".wikitable tr td:first-child a"
tr:first-child
表示“tr
即 第一个 child”。这仅适用于
<tr>
<td>
<a href="" title="">John doe</a>
</td>
<td>
<a href="" title="">other link</a>
</td>
</tr>