Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access DOM element inside $.getJSON

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?

like image 929
jeojavi Avatar asked May 09 '26 23:05

jeojavi


1 Answers

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;
    });
});
like image 187
adeneo Avatar answered May 11 '26 13:05

adeneo



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!