Dusan
Dusan

Reputation: 3478

JQuery select dynamically added elements

In my page i'm generating a list with an ajax call, somehow like this:

for var k in items {
    if (items.hasOwnProperty(k)) {
        someElement.append("<li data-id='"+k+"' class='dynamic'>"+items[k]+"</li>";
    }
}

That works as expected. Now on a button click, I'd like to remove items which have a class '.dynamic'

myBtn.on("click", function() {
    $(".dynamic").remove();
});

But none of the newly added elements gets selected.

I know, how to add listneres to dynamically added elements using .on(). Is there some method to select them also?

Thanks

Upvotes: 0

Views: 434

Answers (1)

Obsidian Age
Obsidian Age

Reputation: 42304

You need to target an element that exists on page load, and make use of event delegation.

The second parameter passed into on() should be the dynamically-created element that you wish to attach the click event handler to:

$("document").on("click", myBtn, function() {
  $(".dynamic").remove();
});

Upvotes: 2

Related Questions