I'm developing an application that iterates over some DOM elements, and performs an Ajax request for each one of those elements. The problem is that I cannot access each DOM element inside the callback function.
$('.class').each(function() {
$.getJSON(url, function(data) {
$(this).attr('id', data.id); // $(this) is not accessible
});
});
Is there a way to solve this?
You should use a variable, as the value of this changes for each function call, and inside the callback for $.getJSON this is no longer the element.
$('.class').each(function() {
var self = this;
$.getJSON(url, function(data) {
self.id = data.id;
});
});
Another option would be the built in arguments in each()
$('.class').each(function(index, element) {
$.getJSON(url, function(data) {
element.id = data.id;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With