javascript - CSS 中的反向查找

标签 javascript html css

我想选择 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/

相关文章:

PHP/Javascript - 从我的大学网站解析 html

javascript - 当鼠标移动到对象上时发生闪烁 - Javascript

javascript - HighCharts 折线图上缺少数据点

javascript - 使用 JavaScript 更新进度条

javascript - Google Chrome 扩展 - 从缓存中获取图像

html - 使用 VBA 访问 iframe 中的对象

javascript - Chrome扩展: XHR request to website,通过类名获取html内容

javascript - 我可以用 .length() 而不是整个文档来计算一个 div 中的元素吗? -jQuery

javascript - drawImage() 按顺序 Canvas 并维护顺序

javascript - cordova中的文本字段显示错误