要使用JavaScript以编程方式选择<img>
元素,您可以使用document.querySelector()
或document.querySelectorAll()
方法。以下是一些示例:
<img>
元素:const imgElement = document.querySelector('img');
<img>
元素:const imgElements = document.querySelectorAll('img');
class
的<img>
元素:const imgElementWithClass = document.querySelector('img.my-image-class');
id
的<img>
元素:const imgElementWithId = document.querySelector('#my-image-id');
src
的<img>
元素:const imgElementWithSrc = document.querySelector('img[src="path/to/image.jpg"]');
alt
文本的<img>
元素:const imgElementWithAlt = document.querySelector('img[alt="Image description"]');
在选择<img>
元素后,您可以对其进行操作,例如更改其属性、添加事件监听器等。
领取专属 10元无门槛券
手把手带您无忧上云