1

I need width and height attributes added to all images on a page via javascript/jquery. This is due to a tool our systems use. I thought a simple each loop, adding height/width attr would suffice. Unfortunately this doesn't seem to work

DEMO https://jsfiddle.net/z86xnqd7/

$('body').find('img').each(function (index) {
    var theWidth = index.width();
    var theHeight = index.height();

    index.attr({
        "width": theWidth,
        "height": theHeight
    });
});

When you inspect element you will notice no width/height attr has been added

  • I don't know what goal you are trying to achieve, but please not that if you're doing this for SEO/PageSpeed purposes this has no use, as the attributes will be added after the images already are loaded. – giorgio Oct 06 '15 at 10:27
  • @giorgio thanks, this isn't for SEO or performance gains. –  Oct 06 '15 at 10:29

3 Answers3

1

jsFiddle : https://jsfiddle.net/CanvasCode/z86xnqd7/6/

You need to do your each on the load event, you need to make sure your image has loaded before you check its height and width. Also you want to use $(this) instead of index.

$(function () {
    $('img').load(function () {
        var theWidth = $(this).width();
        var theHeight = $(this).height();

        $(this).attr({
            "width": theWidth,
                "height": theHeight
        });

    });
});
Canvas
  • 5,779
  • 9
  • 55
  • 98
-1

Problem here is that you try to get the width and height from the index which is just a number and no jQuery object. Try this - it will do the job:

$('body').find('img').each(function(i, elem) {
        var $this = $(this);
        var theWidth = $this.width();
        var theHeight = $this.height();

        $this.attr({"width": theWidth, "height": theHeight});
});

See js fiddle: https://jsfiddle.net/g4nn2pk0/2/

Thariama
  • 50,002
  • 13
  • 138
  • 166
-1

It's because index is real iteration index (e.g. 1, 2...). Use $(this) or add second parameter to function header function (index, element) {}:

$.each($('img'), function () {
    $(this).attr({
        width: $(this).width(),
        height: $(this).height()
    });
});
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • It adds 0 as the height/width ? –  Oct 06 '15 at 10:28
  • @AlwaysLearning Looking at your fiddle, it's because the images are not loaded yet. Wrap this code in a setTimeout and it works. Timeouts are rubbish though; check this question for a better way of determining when images are loaded and call it then: http://stackoverflow.com/questions/910727/jquery-event-for-images-loaded – Whelkaholism Oct 06 '15 at 10:33