0

I would like to collect all Image-Urls of a google Page. With the $get function i managed to list all URLs in my console with console.log(), but if I try to get the URSs in an Array, I have the problem, that 'i' does not increase; its has the amount of the last URL, that means: 200. Tahts my code:

function getUrls2(){

var imgArray = ['1','2'];
var imgUrl = '';
var i = 0;

var imagesDiv = document.getElementsByClassName('rg_bx');
  for (i = 0;i < imagesDiv.length; i++){   

var imgHref = imagesDiv[i].querySelectorAll('a')[0].href;

  $.get(imgHref, null, function(text){
      imgUrl = text.split('</script><title>Google')[1].split('\"')[1];
      if (imgUrl && imgUrl.includes('http')){

      console.log(i+'------>'+imgUrl);

      imgArray.push = (imgUrl);
      console.log(imgArray[i]);   
      }

  });

  };


};

(In the line

var imgHref = imagesDiv[i].querySelectorAll('a')[0].href;

'i' has the right value, but in the $get - function, 'i' is always 200.)

The Console gives the following Output:

200------>https://i1.wp.com/www.littlebighero.ch/wp-content/uploads/2018/01/IMG_3206-e1515821215393-768x1024.jpg?resize=525%2C700&ssl=1 Scratchpad/1:110:19

undefined Scratchpad/1:113:19

200------>https://i0.wp.com/www.littlebighero.ch/wp-content/uploads/2018/01/IMG_3212-e1515821270358-768x1024.jpg?resize=525%2C700&ssl=1 Scratchpad/1:110:19 undefined Scratchpad/1:113:19

200------>https://i.ytimg.com/vi/e8bXuWe0vlk/maxresdefault.jpg Scratchpad/1:110:19 undefined Scratchpad/1:113:19

and so on...

1 Answers1

0

Make a copy of i before using it in the closure:

function getUrls2(){

var imgArray = ['1','2'];
var imgUrl = '';
var _i = 0;

var imagesDiv = document.getElementsByClassName('rg_bx');
for (_i = 0; _i < imagesDiv.length; _i++){   

  var i = _i;
  var imgHref = imagesDiv[i].querySelectorAll('a')[0].href;
  $.get(imgHref, null, function(text){
      imgUrl = text.split('</script><title>Google')[1].split('\"')[1];
      if (imgUrl && imgUrl.includes('http')){

      console.log(i+'------>'+imgUrl);

      imgArray.push = (imgUrl);
      console.log(imgArray[i]);   
      }

  });

  };


};
Blindy
  • 65,249
  • 10
  • 91
  • 131
  • That's exactly what the duplicate advises... – Heretic Monkey Jul 17 '19 at 20:26
  • Imagine that, the correct fix. What's your point? – Blindy Jul 17 '19 at 20:30
  • Duplicate questions should be closed as duplicates, not answered with a duplicate answer. – Heretic Monkey Jul 17 '19 at 20:34
  • Thank you Blindy, I see your anwswer only now cause I didnt expect an answer since its marked as dublicate. But I like your answer more than the 'dublicate' I found. -> this 'dublicate' dont copy 'i', but instead calls a new function with 'i' as passed variable. – Jonas Ruf Aug 08 '19 at 10:25