通过使用 source 属性找到它来选择图像元素

Selecting an image element by using the source attribute to find it

我正在为一个网站编写脚本,我需要更改其中一个图像的图标。问题是网站上的图片只有这样的标签:

<img src="/pic1.png" alt="clear" >

我试过使用以下方法选择图像:

document.querySelector("img[src='pic1.png']");

我试过的是这样的:

var y = document.querySelector("img[src='/pic1.png]'");
y.innerHTML = "<img src='pic2.png' alt='clear'>";

我也试过了

var y = document.querySelector("img[src='/pic1.png]'");
y.src = "/pic2.png";

我是否可以使用 src 属性找到图像,将其分配给变量,然后替换 src

感谢您的帮助:)

你的最后一个例子应该有效

var y = document.querySelector("img[src='/pic1.png']");
y.src = "/pic2.png";
y.load()

如何在该元素上设置一个 Id,然后使用 document.getElementById() select 它,然后您可以继续访问 src 属性,这可以帮助您更改它的价值。