1

I have the following code in an exercise I've made for myself:

var imgs = page.evaluate(function() {
   return document.images;
});

for (var i in imgs){
    console.log("source: " + i.src);
}

but I only get multiple "undefined" messages.

When I try getAttribute('src'), I get:" 'undefined' is not a function... " error message.

I've verified the page has img elements with src attributes.

Solution:

I solved this by as suggested here by:

for (var i = 0; i < imgs.length; i++){
    if (imgs[i])
        console.log("source: " + imgs[i].src);
}

See this question for more information.

Community
  • 1
  • 1
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88

1 Answers1

2

Try this:

for (var i = 0; i < imgs.length; i++) {
    console.log("source: " + imgs[i].src);
}

instead

for (var i in imgs){
    console.log("source: " + i.src);
}
ant_Ti
  • 2,385
  • 16
  • 14
  • I get: TypeError: 'null' is not an object (evaluating 'imgs[i].src') Is it possible I'm missing something more basic than this, and the code I wrote is fine? Edit: OK, I get two of those previous messages and then a message that the page failed to load properly. – Reut Sharabani Apr 04 '13 at 13:16
  • 1
    @ReutSharabani you trying to iterate array as object so `i` will be indexes and not DOM elements – ant_Ti Apr 04 '13 at 13:22
  • 1
    @ReutSharabani if my code give you errors you should first check your `imgs`. Maybe there some odds with images – ant_Ti Apr 04 '13 at 13:25
  • This was eventually resolved by realizing there is a delay between some click event and the server update (updates every 5 minutes or so...) It's working now. – Reut Sharabani Apr 10 '13 at 09:19