treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Remove dynamically appended elements

  • Hey! I have a problem with my JS code:

    I want to achieve that every element with the class .activity is removed. What I do is:

    $(".activity").each(function() {
      $(this).remove();
    })
    

    Basically this works fine the first time. But as the one .activity is removed, I append a new one. And the .remove() function does not work there.
    I saw that there is a method .live() (.on()), but this takes an event like a click. I have no event; I just want to select every appended element and remove it then.

  • When do you want the elements to be removed and why are you adding more?

    This is to closer understand your problem and find a good solution for you.

  • I do an ajax request loading new data. With this data there come new activities. So i want to remove the old ones and add the new ones.
    I hope this is clearer now :)

  • So if I understand it correctly, you're already tying the small bit of code you're showing here to the callback function of the ajax, and when you request the info the first time it works, but not the second?

    I think I might need to see the code a bit more, if you could make a Codepen?