Search code examples
javascriptgreasemonkeyuserscripts

Javascript to double size of all images in all divs of a particular class


So I wrote this javascript to double the images size of all images within all divs of a particular class. Here's what I came up with it.

var lmnts = document.getElementsByTagName('*'), i;
for (i in lmnts) {
    if((' ' + lmnts[i].className + ' ').indexOf(' ' + 'ClassName' + ' ') > -1) {
        var images = document.lmnts[i].getElementsByTagName('img');
        for(var j=0; j<images.length; j++)
        {
            images[j].height *= 2;
            images[j].width *= 2;
        }
    }
}

However I can't get it to work :(

EDIT: It's a user script. So it doesn't work means, it didn't do what it was supposed to do. There are no errors in js console.

On debugging, i find that it enters the first loop just once and then fails after the line var images = document.lmnts[i].getElementsByTagName('img');

EDIT2: It's a userscript to double the image size of all images of class fileThumb in 4chan.org boards.


Solution

  • A major problem would be the var images = document.lmnts[i].getElementsByTagName('img'); line.

    the lmnts is a variable and not a property of the document.

    It should read var images = lmnts[i].getElementsByTagName('img');

    Also, instead of manually looping over all the elements in the DOM and manually testing if the className contains the class you want you could use the document.getElementsByClassName('ClassName') or the more modern document.querySelectorAll('.ClassName'). Using the second method you could also select all images in one go with document.querySelectorAll('.ClassName img').

    So all your code could be simplified to

    var images = document.querySelectorAll('.ClassName img');
    for (var j = 0; j < images.length; j++){
        images[j].height *= 2;
        images[j].width *= 2;
    }
    

    Update (based on comment)

    The images on 4chan have a style attribute applied to them that sets the dimensions while the images[j].height sets the attribute height of the image. Unfortunately the style attribute takes precentence and show the values set from the script are not in effect.

    You should alter the style attribute like this

    var images = document.querySelectorAll('.fileThumb img');
    for (var j = 0; j < images.length; j++){
        var image = images[j],
            initialWidth = parseInt(image.style.width, 10),
            initialHeight = parseInt(image.style.height, 10);
    
        image.style.width = (initialWidth * 2) + 'px';
        image.style.height= (initialHeight * 2) + 'px';
    }