-1
How a dynamically created button can remove itself by clicking on it using jQuery?
var id = 0;
function criar() {
$("#divina").append("<button id=botao" + id +">botao</button><br>");
id +=1;
};
-1
How a dynamically created button can remove itself by clicking on it using jQuery?
var id = 0;
function criar() {
$("#divina").append("<button id=botao" + id +">botao</button><br>");
id +=1;
};
0
Using pure js gets more or less like this:
var id = 0;
function criar() {
$("#divina").append("<button id='botao" + id +"' onclick='remove(\"botao"+id+"\")'>botao"+id+"</button><br>");
id +=1;
};
function remove(elementId){
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
0
Just put an attribute onclick
calling a function and sending the this
(the this
represents the element itself, you do not need to send the id
button):
$("#divina").append("<button onclick='removeBotao(this)' id=botao" + id +">botao</button><br>");
↑
It is also necessary to remove the <br>
after the button. If using jQuery 1.8 forward, use .addBack()
(versions earlier than 1.8, use .andSelf()
):
// até a versão 1.8
function removeBotao(e){
$(e).next().andSelf().remove();
}
// versão 1.8+
function removeBotao(e){
$(e).next().addBack().remove();
}
Testing:
var id = 0;
function criar() {
$("#divina").append("<button onclick='removeBotao(this)' id=botao" + id +">botao</button><br>");
id +=1;
};
function removeBotao(e){
$(e).next().addBack().remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div id="divina"></div>
<button onClick="criar()">Criar</button>
You can use the method .remove()
(does not work in IE) or .outerHTML
to remove the button and select the <br>
with .nextElementSibling
(element that comes after the button):
var id = 0;
function criar() {
$("#divina").append("<button onclick='removeBotao(this)' id=botao" + id +">botao</button><br>");
id +=1;
};
function removeBotao(e){
e.nextElementSibling.outerHTML = '';
e.outerHTML = '';
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divina"></div>
<button onClick="criar()">Criar</button>
Browser other questions tagged jquery
You are not signed in. Login or sign up in order to post.
Already gave a light here and I managed to use with jQuery. Vlw!
– bur