Remove a DOM HTML Element
const button = document.createElement('button');
button.innerText = 'Hello There';
document.body.appendChild(button);
// click anywhere
document.body.addEventListener('click', () => {
if (button.parentNode != null) {
button.parentNode.removeChild(button);
}
});
In vanilla js you’ll find yourself checking if an HTML DOM element can be removed, by seeing if it has a parent (as seen above). Forgetting to do so is the source of many errors.
With the death of IE11 you can use remove()
const button = document.createElement('button');
button.innerText = 'Hello There 2';
document.body.appendChild(button);
// click anywhere
document.body.addEventListener('click', () => {
button.remove();
});
No error occurs when calling remove()
on something that is already removed… just like the old jQuery days 😉