Home > Net >  Reverse lookup in CSS
Reverse lookup in CSS

Time:04-06

I want to select img tags which do not wrap under table. The code below should return only 1 as length as this HTML only has 1 img tag not under a table.

Note : Changing the markup/style isn't possible.

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  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>

CodePudding user response:

To target elements that don't satisfy a given criteria, you can use the :not() pseudo class in 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  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?

Sure.

img:not(table) selects all img elements that are not table elements.

img:not(table img) selects all img elements who are not img elements that are descendants of table elements.

In other words, anything inside :not() you can kinda think of as global scope, it doesn't know what's before/after it, so pretend you're applying it on the * universal selector wherever you use it.

  • Related