So i have a div with a lot of images:
<div id="d1">
<img id="img1" src="resources/square.png"/>
<img id="img2" src="resources/square.png"/>
...
</div>
my css file looks like this:
#d1 img {
width: 5%;
}
So, instead of looping over all the images, is it possible to modify the width attribute above using javascript? (I want to modify every image's width)
You can use the querySelectorAll and combine it with forEach to set an attribute to all images within the container.
window.onload = function loop() {
document.querySelectorAll('#d1 img').forEach(el => el.setAttribute('width', '300'));
}
<div id="d1">
<img id="img1" src="https://via.placeholder.com/100.jpg;"/>
<img id="img2" src="https://via.placeholder.com/100.jpg;"/>
<img id="img3" src="https://via.placeholder.com/100.jpg;"/>
<img id="img4" src="https://via.placeholder.com/100.jpg;"/>
<img id="img5" src="https://via.placeholder.com/100.jpg;"/>
</div>
You don't have to loop. If you use CSS variables you can set up a variable in your CSS file that img initially uses, and then you can use JS to update that variable for all the images.
setTimeout(() => {
document.documentElement.style.setProperty('--width', '50%');
}, 2000);
:root { --width: 5%; }
#d1 img { width: var(--width); }
<div id="d1">
<img id="img1" src="resources/square.png"/>
<img id="img2" src="resources/square.png"/>
</div>
Something like this, using querySelectorAll and a for loop can do the trick and should give you what you want.
const images = document.querySelectorAll('#d1 img');
for(var i = 0; i < images.length; i++){
images[i].setAttribute("width", "5%") //Change this to any percent value.
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<div id="d1">
<img id="img1" src="https://cdn.pixabay.com/photo/2017/01/08/13/58/cube-1963036__340.jpg"/>
<img id="img2" src="https://cdn.pixabay.com/photo/2017/01/08/13/58/cube-1963036__340.jpg"/>
<img id="img3" src="https://cdn.pixabay.com/photo/2017/01/08/13/58/cube-1963036__340.jpg"/>
</div>
</body>
</html>
An alternative to using a for loop in querySelectorAll can be to use a forEach loop, which will give you the same result.