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.

downloadDownload PNG downloadDownload JPEG downloadDownload SVG

Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!

Click to optimize width for Twitter