How to remove existing HTML elements in JavaScript?

This article discusses how to delete existing HTML elements in JavaScript. To remove HTML elements, you first need to select the element from the document, then use methods like remove() and removeChild() to delete them from the DOM.

Using the remove() Method

The remove() method directly removes an element from the DOM. It's the simplest approach for modern browsers.

Syntax

element.remove();

Example

<!DOCTYPE html>
<html>
<head>
   <title>Remove Element Example</title>
</head>
<body>
   <h2 id="heading">This heading will be removed</h2>
   <p id="paragraph">This paragraph will remain</p>
   <button onclick="removeHeading()">Remove Heading</button>
   
   <script>
      function removeHeading() {
         const heading = document.getElementById('heading');
         heading.remove();
         console.log('Heading removed successfully');
      }
   </script>
</body>
</html>
Heading removed successfully

Using removeChild() Method

The removeChild() method removes a child element from its parent. You need to access the parent element first.

Syntax

parentElement.removeChild(childElement);

Example 1: Basic removeChild()

<html>
<body>
   <div id="container">
      <p id="first">First paragraph</p>
      <p id="second">Second paragraph</p>
   </div>
   
   <script>
      const container = document.getElementById("container");
      const firstPara = document.getElementById("first");
      container.removeChild(firstPara);
      console.log('First paragraph removed');
   </script>
</body>
</html>
First paragraph removed

Example 2: Using parentNode

<!DOCTYPE html>
<html>
<head>
   <title>Remove Element with parentNode</title>
</head>
<body>
   <ul id="list">
      <li id="item1">Item 1</li>
      <li id="item2">Item 2</li>
      <li id="item3">Item 3</li>
   </ul>
   <button onclick="removeSecondItem()">Remove Item 2</button>
   
   <script>
      function removeSecondItem() {
         const item2 = document.getElementById('item2');
         item2.parentNode.removeChild(item2);
         console.log('Item 2 removed using parentNode');
      }
   </script>
</body>
</html>
Item 2 removed using parentNode

Comparison

Method Syntax Browser Support Complexity
remove() element.remove() Modern browsers Simple
removeChild() parent.removeChild(child) All browsers Requires parent reference

Key Points

  • remove() is simpler and more direct for modern applications
  • removeChild() provides better browser compatibility
  • Always select elements properly before attempting removal
  • Removed elements are completely deleted from the DOM

Conclusion

Use remove() for modern browsers as it's cleaner and more straightforward. Use removeChild() when you need broader browser compatibility or are working with parent-child relationships explicitly.

Updated on: 2026-03-15T23:18:59+05:30

47K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements