Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript 'for in' statement giving unpredicted results

I have the following code:

var images = document.getElementsByTagName('img');

if (screen.width > 640) {
    for (var image in images) {
        image = images[image];

        console.log(image['src']);
    }
}

There is only one image on the page, but for some reason the for ... in statement is looping through images three times. Why is this?

Example: http://jsfiddle.net/OliverJAsh/C8egs/


1 Answers

You're not just looping through the list of elements, but also the named methods:

  • length
  • item
  • namedItem

The correct approach is:

for (var i=0; i<images.length; i++) {
    var image = images[i];

    console.log(image['src']);
}

Instead of using document.getElementsByTagName('img'), you can also use document.images.

http://jsfiddle.net/C8egs/2/

like image 152
Rob W Avatar answered Feb 15 '26 04:02

Rob W



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!