我想选择 img
标签,这些标签不包含在 table
下。下面的代码应该只返回 1 的长度,因为这个 HTML 只有 1 个 img
标签不在 table
下。
注意:无法更改标记/样式。
console.log(document.querySelectorAll('img').length)
<table align="center">
<tbody>
<tr>
<td style="text-align: center;">
<a href="https://xxx" imageanchor="1" style="margin-left: auto; margin-right: auto;">
<img border="0" src="https://xxx" original="https://xxx" style="">
</a>
</td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center;">Double Trailing</td>
</tr>
</tbody>
</table>
<a href="https://xxx" imageanchor="1" style="margin-left: auto; margin-right: auto;">
<img border="0" src="https://xxx" original="https://yyy" style="">
</a>
最佳答案
要定位不满足给定条件的元素,您可以使用 :not()
CSS 中的伪类:
console.log(document.querySelectorAll('img:not(table img)').length)
<table align="center">
<tbody>
<tr>
<td style="text-align: center;">
<a href="https://xxx" imageanchor="1" style="margin-left: auto; margin-right: auto;">
<img border="0" src="https://xxx" original="https://xxx" style="">
</a>
</td>
</tr>
<tr>
<td class="tr-caption" style="text-align: center;">Double Trailing</td>
</tr>
</tbody>
</table>
<a href="https://xxx" imageanchor="1" style="margin-left: auto; margin-right: auto;">
<img border="0" src="https://xxx" original="https://yyy" style="">
</a>
Can you please explain why this img:not(table) does not work?
img:not(table)
选择所有不是 table 元素的 img 元素。
img:not(table img)
选择不是作为 table 元素后代的 img 元素的所有 img 元素。
换句话说,:not()
中的任何内容你都可以认为是全局范围,它不知道它之前/之后是什么,所以假装你在 *
通用选择器,无论您在哪里使用它。
关于javascript - CSS 中的反向查找,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71761914/