Remove a DOM element by ID using JavaScript

avatar

Borislav Hadzhiev

Sat Jan 01 20222 min read

Remove a DOM element by ID using JavaScript #

To remove a DOM element by id:

  1. Select the DOM element using the document.getElementById() method.
  2. Call the remove() on the element, e.g. element.remove().
  3. The remove() method removes the element from the DOM.

Here is the HTML for the examples in this article.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Box 1</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const element = document.getElementById('box'); element.remove();

We used the document.getElementById to select an element by its id.

The getElementById() method returns an Element whose id matches the provided string.

If there is no element with the specified id in the DOM, the method returnsnull.

You can use the optional chaining operator to avoid getting an error if the element does not exist.

index.js
const element = document.getElementById('box'); element?.remove();

If the element variable stores a null or undefined value, the optional chaining operator will short-circuit instead of calling the remove() method.

The last step is to use the Element.remove() method to remove the element from the DOM.

Note that removing an element also removes its children.

If you need to remove the element without removing its children, use this approach instead.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ๐Ÿ‘‡๏ธ Only remove this div (not children) --> <div id="parent"> <span>Child 1</span> <span>Child 2</span> </div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

index.js
const element = document.getElementById('parent'); element.replaceWith(...element.childNodes);

To remove an element without removing its children, we basically replace the element with its children.

The code in the example only removes the div element with id of parent, without removing the span elements located inside of the div.

If you need to handle the scenario where the element does not exist, use the optional chaining operator (?.).

index.js
const element = document.getElementById('parent'); element?.replaceWith(...element.childNodes);

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee