首页 > 解决方案 > 为不在锚点内的所有图像添加事件侦听器

问题描述

如何在没有原生JavaScript 中的任何库(没有任何库)的情况下选择<img>不在锚点内的所有元素?<a>最精通性能的方法是什么?

标签: javascripthtmldom

解决方案


结果很简单:

// Use CSS-like selector
const images = document.querySelectorAll(":not(a) > img");

// Foreach it

images.forEach((img) => {
// Use the img variable
}

推荐阅读