我想 Select img个标签,它们不在table下包装.下面的代码应该只返回1个长度,因为这个HTML只有1img个标记,不在table下.

Note :不可能更改标记/样式.

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>

推荐答案

要以don't满足给定条件的元素为目标,可以在CSS中使用:not()伪类:

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>

你能解释一下为什么这个img:not(表)不起作用吗?

当然

img:not(table) Select 所有不是表格元素的img元素.

img:not(table img) Select 所有不是img元素的img元素,这些img元素是表元素的后代.

换句话说,:not()以内的任何东西都可以被认为是全局范围,它不知道它之前/之后是什么,所以假设你正在*通用 Select 器上应用它,无论你在哪里使用它.

Javascript相关问答推荐

在JS中转换mysql UTC时间字段?

带对角线分隔符的图像滑动器

使用JavaScript重命名对象数组中的键

在JavaScript中检索一些文本

当promise 在拒绝处理程序被锁定之前被拒绝时,为什么我们会得到未捕获的错误?

Vue:ref不会创建react 性属性

Bootstrap动态选项卡在切换选项卡后保持活动状态,导致元素堆叠

被CSS优先级所迷惑

Cookie中未保存会话数据

. NET中Unix时间转换为日期时间的奇怪行为

使用i18next在React中不重新加载翻译动态数据的问题

jQuery s data()[storage object]在vanilla JavaScript中?'

如何通过使用vanilla JS限制字体大小增加或减少两次来改变字体大小

为什么useState触发具有相同值的呈现

制作钢琴模拟器,并且在控制台中不会执行或显示该脚本

我怎么在JS里连续加2个骰子的和呢?

用于部分字符串的JavaScript数组搜索

FireBase FiRestore安全规则-嵌套对象的MapDiff

我怎样才能点击一个元素,并获得一个与 puppeteer 师导航页面的URL?

rxjs在每次迭代后更新数组的可观察值