In this article, we’re going to learn how to easily remove an element in the HTML DOM by its ID using JavaScript.
The Element remove() Method
To remove a DOM element by ID, use the getElementById()
method to select the element with the ID, then call the remove()
method on the element.
For example:
index.html
<!DOCTYPE html>
<html>
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
<div class="box" id="box-1">This is a box</div>
<script src="index.js"></script>
</body>
</html>
Here’s how we can remove the element with the box-1
id:
index.js
const box = document.getElementById('box-1');
box.remove();
The getElementById()
method takes a string and returns the element in the DOM with an ID that matches the string.
If there is no element with a matching ID, getElementByID()
returns null
.
index.js
const box = document.getElementById('box-5');
console.log(box); // null
We can use the optional chaining operator (?.
) to call remove()
to avoid causing an error if there is no DOM element with the ID.
Instead of causing an error, the optional chaining operator will prevent the method call and return undefined
.
index.js
const box = document.getElementById('box-5');
box?.remove(); // no error thrown
How to Remove a DOM Element without Removing its Children
The remove()
method removes a DOM element along with its children. What if want to keep the children of the element in the DOM?
index.html
<!DOCTYPE html>
<html>
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
<div id="parent">
<p>Child 1</p>
<p>Child 2</p>
</div>
<script src="index.js"></script>
</body>
</html>
To remove the div
element with the ID parent
but keep its children, we can call the replaceWith()
method on the div
, passing the children of the element as arguments.
index.js
const element = document.getElementById('parent');
element.replaceWith(...element.childNodes);
Now the markup of the document will look like this:
<!DOCTYPE html>
<html>
<head>
<title>Coding Beauty Tutorial</title>
</head>
<body>
<p>Child 1</p>
<p>Child 2</p>
<script src="index.js"></script>
</body>
</html>
The childNodes
property returns a list of the child nodes of an element. We use it to get the children of the element.
The replaceWith()
method replaces an element in the DOM with a set of Node
or string objects. We call it on the element to replace it with the children.
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.