Home > other >  Modifying all images from div using css and Javascript
Modifying all images from div using css and Javascript

Time:05-11

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)

CodePudding user response:

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>

CodePudding user response:

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.

CodePudding user response:

You don't have to loop. If you use CSS variables you can set that up in your CSS file, and then use JS to update that variable for all the images.

setTimeout(() => {
  document.documentElement.style.setProperty('--width', '50%');
}, 2000);
:root { --width: 5%; }
img { width: var(--width); }
<div id="d1">
  <img id="img1" src="resources/square.png"/>
  <img id="img2" src="resources/square.png"/>
</div>

  • Related