简体   繁体   中英

How to remove a button when clicked

I'm not very familiar with Javascript and I'm doing a function where if a button is clicked, it would remove the button using its ID.

I have tried doing different solutions where I would get the IDs but I am stuck about the logic of it.

When I click the button it does not do anything.

 var myBtn = document.getElementById("my-btn"), mySpan = document.createElement("span"); mySpan.innerHTML = myBtn.innerHTML; myBtn.parentNode.replaceChild(mySpan, myBtn); < 
 <div> <button id="my-btn">Hello</button> </div> 

Use the button's onclick event for that:

 var button = document.getElementById("my-btn"); button.onclick = function() { //this code will execute whenever the button is clicked //inside the handler, "this" refers to the button this.parentNode.removeChild(button); } 
 <div> <button id="my-btn">Hello</button> </div> 

HTML:

<button type="button" id="MyButton">Click me</button>

removing the button clicked:

const btn = document.getElementById('MyButton');

btn.addEventListener("click", function () {
this.remove();
});

to just hide it replace this.remove(); by this.classList.add('hidden'); and with css you can do .hidden {display:none;} OR adding this.setAttribute('hidden', 'hidden');

remove docs on MDN

HTML

<button id="me"onclick="myFunction()">Try it</button>

JS

 <script>
  function myFunction() {
  var x = document.getElementById("me");
  x.remove();
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM