JAVASCRIPT

Remove an Element from the Document Object Model (DOM)

Learn the straightforward method to remove a specific HTML element from the DOM using its parent's `removeChild()` method or the element's own `remove()` method in JavaScript.

function removeElementById(elementId) {
  const elementToRemove = document.getElementById(elementId);
  if (elementToRemove) {
    // Modern approach:
    elementToRemove.remove();
    return true;

    // Older approach (also works):
    // if (elementToRemove.parentNode) {
    //   elementToRemove.parentNode.removeChild(elementToRemove);
    //   return true;
    // }
  }
  return false;
}

// Example Usage:
// Assume you have a paragraph with id="disappearingText"
// <p id="disappearingText">I will be removed!</p>
// <button onclick="removeElementById('disappearingText')">Remove Text</button>
How it works: This snippet shows two common ways to remove an element from the DOM. The modern and simpler approach is to call `element.remove()` directly on the element you wish to delete. Alternatively, you can access the element's `parentNode` and use `parentNode.removeChild(element)` to achieve the same result.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs