Event Delegation is the way to do it.
When you add event to .edit-button
directly, at the time of loading the document, browser attaches that event listener to only the currently existing .edit-button
elements. It doesn't get executed automatically for the newly created elements with the same class.
What you could do is put your event biding and listener code in a function and call it each time you add a new element to the DOM. But that's considered a bad practice.
Welcome, Event Delegation.
The idea is to attach the event to a parent/ancestor element which is not dynamic and trigger the event only when the event target is your specified element( matched with some sort of selector like class or ID).
In your case, the updated event binding code would look like this.
$(document.body).on("click", ".edit-button", function(){
//whatever you want to do in here.
});
and then, you can continue to add classes to newly created elements like you did...
var editLink = document.createElement("a");
editLink.setAttribute("class", "edit-button");
The event would still work.
This way you only attach the event once.
If your buttons/links are going to be contained in a container div
or something similar, attach the event to that container instead of body.
$(".class-of-the-container").on("click", ".edit-button", function(){
//whatever you want to do in here.
});