How to Destroy HTML Elements Using JavaScript?

Estimated read time 1 min read

You can destroy an HTML element using JavaScript by removing it from its parent element. This can be done by using the removeChild method of the parent element.

Here’s an example of how to remove an element with an id of “myElement”:

<!DOCTYPE html>
<html>
  <head>
    <title>My Website</title>
  </head>
  <body>
    <div id="myElement">This is my element</div>
    <button id="removeButton">Remove Element</button>
    <script>
      let removeButton = document.getElementById("removeButton");
      let myElement = document.getElementById("myElement");
      removeButton.addEventListener("click", function() {
        myElement.parentNode.removeChild(myElement);
      });
    </script>
  </body>
</html>

In this example, we first use JavaScript to select the element with an id of “myElement” and the button element with an id of “removeButton”. We then attach an event listener to the button that listens for the click event. When the button is clicked, the function inside the event listener is called, which removes the element with the id of “myElement” from its parent node using the removeChild method.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply