theinvisibleduck theinvisibleduck - 3 months ago 10
jQuery Question

jquery get not allowing x[i] inside of function

I am trying to write a JQuery get that returns true if there is an embedded youtube video at the other end of the URL, and if so update the div to mention that.

My Code so far:

var x = document.getElementsByClassName("videoplace");
var lim=x.length;
for (var i = 0; i <lim; i++) {
$.get(x[i].innerHTML, function(data){if(data.indexOf("youtube.com/embed")>-1)
{
x[i].innerHTML = "Video Exists";
}
});
}


When I run this I get an error in the console that says "TypeError: Cannot set property 'innerHTML' of undefined" I have tried a plethora of alternatives and while the get function is working, and the if only fires if it returns true correctly, it doesnt correctly recognize where to put the "Video exists" text.

Answer

By the moment callback function(data) run for loop is over Correct call is

var x = document.getElementsByClassName("videoplace");
var lim=x.length;
for (var i = 0; i <lim; i++) {
        (function(j){$.get(x[j].innerHTML, function(data){if(data.indexOf("youtube.com/embed")>-1)
        {
            x[j].innerHTML = "Video Exists";
        }
        }))(i);
}
Comments