I need to resize 3 images with javascript. How can i do that without having an ID and without having possibility to add one? I have tried this but i don t know how to select all images(i need to set the width to 50px).
let images=document.querySelector('img');
images.setAttribute("width",50);
Is document.querySelectorAll() what you're looking for? document.querySelectorAll() will select all elements matching a certain selector, not just the first.
In your case, it might be
let images=document.querySelectorAll('img');
images.forEach(img => img.setAttribute("width",50));
If you can't use CSS to change the image width pick up the images with querySelectorAll and then iterate over the node list of images and change the width of each one.
const images = document.querySelectorAll('img');
images.forEach(image => image.setAttribute('width', '50px'));
<img src="https://dummyimage.com/100x100/000/fff" />
<img src="https://dummyimage.com/100x100/000/fff" />
<img src="https://dummyimage.com/100x100/000/fff" />
You can do it with querySelectorAll
changeSize = () => {
let images = document.querySelectorAll('img');
for (let i = 0; i < images.length; i++) {
images[i].style.width = "100px";
}
}
originSize = () => {
let images = document.querySelectorAll('img');
for (let i = 0; i < images.length; i++) {
images[i].removeAttribute("style");
}
}
.images {
display: flex;
}
.images img {
margin: 1em 1em 0 0;
}
<button onclick="changeSize()">Change Size</button>
<button onclick="originSize()">Origin Size</button>
<div class='images'>
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
<img src="https://cdnp2.stackassets.com/b1284961a6fbcbcfabe6f69c2ae4219ff6daa5e0/store/opt/596/298/1ca89e578fc4e326fe08196758c1688929acc8c5eeb8572e2282628cad78/product_30565_product_shot_wide.jpg" />
</div>