为何HTML中table>tbody:nth-child(1)失效,而:nth-child(2)生效?
问题解析:为什么
tbody:nth-child(1)无法选中元素,而tbody:nth-child(2)可以? 核心原因在于CSS :nth-child()选择器的匹配逻辑:它是基于父元素下所有子元素的位置排序,而非同类型元素的位置。
你的表格结构中,<table>的直接子元素顺序是:
<thead><tbody>
- 当使用
table>tbody:nth-child(1)时,它要求匹配<table>的第1个子元素,且该元素必须是<tbody>。但<table>的第1个子元素是<thead>,不符合<tbody>的类型要求,因此匹配结果为0。 - 当使用
table>tbody:nth-child(2)时,它要求匹配<table>的第2个子元素,且该元素是<tbody>。你的<tbody>恰好是<table>的第2个子元素,因此能成功匹配,返回结果为1。
如果需要按同类型元素的位置选择,应该使用:nth-of-type()选择器。比如table>tbody:nth-of-type(1),它会忽略父元素下的其他类型子元素,直接匹配第一个<tbody>,此时返回结果为1。
示例代码验证:
<table> <thead> <tr><th>表头</th></tr> </thead> <tbody> <tr><td>内容行</td></tr> </tbody> </table> <script> console.log(document.querySelectorAll('table>tbody').length); // 1 console.log(document.querySelectorAll('table>tbody:nth-child(1)').length); // 0 console.log(document.querySelectorAll('table>tbody:nth-child(2)').length); // 1 console.log(document.querySelectorAll('table>tbody:nth-of-type(1)').length); // 1 </script>
内容的提问来源于stack exchange,提问作者yaner
相关产品推荐
相关产品推荐

