Borislav Hadzhiev
Last updated: Jan 1, 2022
Check out my new book
To remove a DOM element by id:
document.getElementById()
method.remove()
on the element, e.g. element.remove()
.remove()
method removes the element from the DOM.Here is the HTML for the examples in this article.
<!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.
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.
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.
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.
If you need to remove the element without removing its children, use this approach instead.
<!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.
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.
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 (?.).
const element = document.getElementById('parent'); element?.replaceWith(...element.childNodes);