How to Add a Close Button in div to Close the div with JavaScript?

Sometimes, we want to add a close button in div to close the div with JavaScript.

In this article, we’ll look at how to add a close button in div to close the div with JavaScript.

Add a Close Button in div to Close the div with JavaScript

To add a close button in div to close the div with JavaScript, we can add a click listener to the close button.

For instance, we can write:

<div>
  <button id='close'>
    close
  </button>
  <h3>title</h3>
  <p class="text">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit.
  </p>
</div>

to add a close button in a div.

Then we write:

window.onload = () => {
  document.getElementById('close').onclick = function() {
    this.parentNode.remove()
    return false;
  };
};

We set the window.onload property to a function that runs when the DOM is loaded.

In the function, we select the close button with document.getElementById('close').

And we set the onclick property to a function that removes the the parent of the close button, which is the div.

We get the parent of the close button with this.parentNode.

Then we call remove on it to remove the parent node which is the div.

And we return false to prevent the default action.

Now when we click the close button, the div is removed from the screen.

Conclusion

To add a close button in div to close the div with JavaScript, we can add a click listener to the close button.