Using javascript to change the width of multiple images with the same identifier

advertisements

I have a page with multiple images with the same id, I want to use javascript to size each of these depending on their original size. It only seems to check the first instance of the image and not the others, is there any way to get this working on all images?

<img id="myImg" src="compman.gif" width="100" height="98">
<img id="myImg" src="compman.gif" width="49" height="98">

<p id="demo"></p>

<button onclick="myFunction()">Try it</button>

<script>

<script>
var x = document.getElementById("myImg").width;
var yourImg = document.getElementById('myImg');
if(x < 50) {
    yourImg.style.height = '100px';
    yourImg.style.width = '200px';
}
</script>


The reason this isnt working is that getElementById is intended to find and return a single element with that Unique element Id. If you have two elements with the same Id, only the first is returned.

So to start off with you would need to make sure that your images share a common class, instead of the same Id, like so:

<img class="myImg" src="compman.gif" width="100" height="98">
<img class="myImg" src="compman.gif" width="49" height="98">

Then instead of using document.getElementById you should use document.querySelectorAll() which will return all elements which match the selector (as a NodeList). document.querySelectorAll on MDN

Then you can turn the NodeList returned by querySelectorAll into a normal array of images using Array#slice Array#slice on MDN.

Once done then you can itterate over each of the images (Array#forEach) and set their width/height if appropriate

So here is a possible solution for what you need to do, with comments:

var images = document.querySelectorAll('.myImg'), // Fetch all images wih the 'myImg' class
    imageArray = Array.prototype.slice.call(images); // Use Array.prototype.slice.call to convert the NodeList to an array

imageArray.forEach(function (img) { // Now itterate over each image in the array
   if (img.width < 50) { // If the width is less than 50
       img.style.setAttribute('height', '100px'); // Set the height and width
       img.style.setAttribute('width', '200px');
   }
});

You will also need to make sure that the code will be executed, if you are using jQuery, put the code above in an document ready function, or if you are going to use the button which you currently have. Then put the javascript above into the myFunction function your buttons onclick event would call.