我想 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相关问答推荐

如何使用3个部件之间的路由?

验证嵌套 colored颜色 代码的结果

Toast函数找不到其dis

如何在加载的元数据上使用juserc和await中获得同步负载?

如何让\w token 在此RegEx中表现得不贪婪?

根据总价格对航班优惠数组进行排序并检索前五个结果- Angular HTTP请求

使用AJX发送表单后,$_Post看起来为空

通过在页面上滚动来移动滚动条

IMDB使用 puppeteer 加载更多按钮(nodejs)

字节数组通过echo框架传输到JS blob

按下同意按钮与 puppeteer 师

Angular 17—每当一个布尔变量变为真时触发循环轮询,只要它保持为真

如何在Javascript中使用Go和检索本地托管Apache Arrow Flight服务器?

如何为我的astro页面中的相同组件自动创建不同的内容?

无法检测卡片重叠状态的问题

我可以使用使用node.js创建的本地主机来存储我网站上提交的所有数据吗?没有SQL或任何数据库.只有HTML语言

如何将innerHTML字符串修剪为其中的特定元素?

从Nextjs中的 Select 项收集值,但当单击以处理时,未发生任何情况

如何在我的Next.js项目中.blob()我的图像文件?

Node.js API-queryAll()中的MarkLogic数据移动