JavaScript - Delete HTML elements
A simple code example for deleting the tags of specified HTML elements using JavaScript.
In HML, we have placed elements to be deleted and a delete button.
<div>
<div id="target">Element to delete</div>
<button type="button" id="delete-btn">Delete Button</button>
</div>
The JavaScript implements the click event of the delete button using addEventListener()
, and removes it using remove()
if the target HTML element exists.
// Create click event for delete button
document.querySelector('#delete-btn').addEventListener('click', () => {
// Remove HTML element if it exists
if (document.querySelector('#target')) {
document.querySelector('#target').remove();
}
});