)
}
}
)
(
}
{
)
)
(
)
(
(
{
}
)
(
)
}
)
)
{
(
(
)
)
}
)
(
}

Remove a DOM HTML Element

  1. const button = document.createElement('button');
  2. button.innerText = 'Hello There';
  3. document.body.appendChild(button);
  4.  
  5. // click anywhere
  6. document.body.addEventListener('click', () => {
  7.   if (button.parentNode != null) {
  8.     button.parentNode.removeChild(button);
  9.   }
  10. });

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()

  1. const button = document.createElement('button');
  2. button.innerText = 'Hello There 2';
  3. document.body.appendChild(button);
  4.  
  5. // click anywhere
  6. document.body.addEventListener('click', () => {
  7.    button.remove();
  8. });

No error occurs when calling remove() on something that is already removed… just like the old jQuery days 😉

// dom // javascript // ui
snippet.zone ~ 2021-22 /// {s/z}