我知道如何在 <img>
上设置 ALT 标签如果我对页面上的所有图像都有类或全局,但是如何对没有 id 或类的特定图像执行此操作?我能否以某种方式使用父 DIV 来引用图像并添加 alt 标签?
<div id="table_processing">
<img src="processing_report.gif"> Loading Report List...
</div>
最佳答案
我建议使用 document.querySelector()
,它允许您使用 CSS(类似 jQuery)选择器来选择图像。
像这样:
var image = document.querySelector("#table_processing img");
然后您可以设置 alt
属性:
image.alt = "Our New Alt Text";
或
image.setAttribute("alt", "our New Alt Text");
这是一个演示:
var image = document.querySelector("#table_processing img");
image.alt = "Our New Alt Text";
<div id="table_processing">
<img src="http://via.placeholder.com/350x150"> Loading Report List...
</div>
关于javascript - 使用 JavaScript 设置 <img> alt 标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47943901/