My answer is based on the case of inserting ONLY 1 button with the id #BtnRemove
, as reported 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, as a id
should be unique on the page. If this is the case, you need to do otherwise using class
instead of id
.
You can use document.querySelector("body").addEventListener("click"...
checking whether the target
of the event has the id
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 that variable) returns the called event. The property target
returns the element target the event (in this case, the clicked item) and .id
the attribute id
of the element.
Checking in the if
if the id
is the of the element who matters ("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>
Well, first, you don’t have a button
<div>
. Now, what you mean by clicking the button with pure Javascript and why this restriction since you are already using Jquery?– Leandro Angelo
@Leandroangelo A div (or any other element) can become a button also when you format to work as a button. In this case it may not be a button itself, but it only has the function of being a :D button
– Sam
@dvd This I know, but it is appearance or role, but this remains a <div>. And no click event behavior has been presented, and maybe the Javascript constraint may be because AP is trying to bind when the element does not yet exist in the DOM and thinks that by Jquery account. (speculating)
– Leandro Angelo
@Oclácio, this button is generated as? do you have control over this code? there will be more than one button equal on the page?
– Sergio
There are no other buttons with this ID, it is unique on the page.
– Oclácio Silva
When I give a Document.getElementById("Btnremove"); the console returns me NULL, returns null when it is generated dynamically. When I put it manually the console returns me Object. That’s what I want to understand Why the console returns NULL when the ID is generated dynamically and how can I locate this ID and Click On It.
– Oclácio Silva