javascript for image get image width and height and add height and width attribute on those img tag

PHOTO EMBED

Mon Feb 06 2023 13:00:53 GMT+0000 (Coordinated Universal Time)

Saved by @mickeldav #javascript #shopify

Here is a JavaScript code snippet that will get the width and height of all images on a page and add the width and height attributes to each img tag:



var images = document.getElementsByTagName("img");
for (var i = 0; i < images.length; i++) {
    var img = images[i];
    var width = img.naturalWidth;
    var height = img.naturalHeight;
    img.setAttribute("width", width);
    img.setAttribute("height", height);
}


This code uses the document.getElementsByTagName method to select all img tags on the page, then loops through each one using a for loop. The naturalWidth and naturalHeight properties of each img tag are used to get its dimensions, and the setAttribute method is used to add the width and height attributes with the appropriate values.



content_copyCOPY