jQuery unable to addClass to multiple dynamically created elements

I am unable to resolve the following issue with my Twitch.tv project. When I run the following code

('.offline').each(function(){ (this).addClass(‘hide’);

jQuery unable to addClass to multiple dynamically created elements with the same class.


You call hideOffline right after getUser(). Because getUser calls getStatus in the $.each loop, each getStatus call performs an $.ajax call which takes time to get the data back for each call. Since $.ajax runs asynchronously, other code which can run will continue running, which is why your hideOffline function finishes before a single $.ajax call has finished. The following code in the hideOffline function does nothing, because none of the divs created by the printStatus function have the “offline” class when hideOffline runs.

You should add the class “offline” inside the success function of the $.ajax call. You will have to modify your logic a bit, but that is the best place to add the class.

Thanks for the information.

You could also modify your printStatus function as:

  function printStatus(index) {
    // output status of user
    var classesToAdd = 'profile ' + userArr[index].status;
    if (userArr[index].status === "offline") {
      classesToAdd += " hide";
      '<div class="' + classesToAdd + '">' +
        '<img src="' +
        userArr[index].logo +
        '">' +
        userArr[index].username +
        " is " +
        userArr[index].status +
        ". " +
        userArr[index].game +