Quiero seleccionar etiquetas img que no se ajusten debajo table . El siguiente código debe devolver solo 1 como longitud, ya que este HTML solo tiene 1 etiqueta img que no está debajo de una table .
Nota: No es posible cambiar el marcado/estilo.
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>Para apuntar a elementos que no satisfacen un criterio dado, puede usar la pseudo clase :not() en 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>¿Puede explicar por qué este img: not (tabla) no funciona?
Por supuesto.
img:not(table) selecciona todos los elementos img que no son elementos de tabla.
img:not(table img) selecciona todos los elementos img que no son elementos img que son descendientes de los elementos de la tabla.
En otras palabras, cualquier cosa dentro de :not() puede pensarse como un alcance global, no sabe qué hay antes/después, así que finja que lo está aplicando en el * selector universal donde sea que lo use.