My answer is based on the case of inserting ONLY 1 button with id #BtnRemove
, as informed in the question:
I have a remove button that is generated via Jquery [...]
If you are inserting several of these buttons, it is already incorrect because you are duplicating id
s, since a id
must be unique on the page. If this is the case, you must do it using class
instead of id
.
You can use document.querySelector("body").addEventListener("click"...
checking that target
of event has id
of button:
document.querySelector("body").addEventListener("click", function(e){
if(e.target.id == 'BtnRemove'){
// ação ao clicar no botão
}
});
The variable e
(you can use any name for this variable) returns the called event. The target
property returns the target element of the event (in this case, the element clicked) and .id
the attribute id
of the element.
Checking in if
if id
is that of the question element ("Remove" button), you can perform the action you want.
Illustrative example:
document.querySelector("body").addEventListener("click", function(e){
if(e.target.id == 'BtnRemove'){
console.log("botão clicado");
}
});
$("span").html("<div id='BtnRemove'>Remover</div>");
#BtnRemove {
padding: 10px;
color: #fff;
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span></span>