We can use JavaScript to remove an element from the DOM by simply using the remove() method.
document.getElementById("div1").remove();
Let’s say we have the following html:
This is a div that will remain.
This is a div that we can Remove with JavaScript.
This is a div that will remain.
Next, we want to hide the div with id #div2, so we will target the element using the getElementById() method. We will then simply call the remove() method on this div to remove it from the DOM.
document.getElementById("div2").remove();
Let’s put this all together and see the result.
Initial Code:
Full Code:
This is a div that will remain.
This is a div that we can Remove with JavaScript.
This is a div that will remain.
Result:
Note that when we remove an element from the DOM, we can no longer access that element. So trying to use some code like document.getElementById("div2").style.display = "block";
would do nothing and return an error as the div, #div2 no longer exists in the DOM.
Using JavaScript to Remove an Element From the DOM with a Click
We can use JavaScript to remove a Div very easily by combining the remove() method with an onclick event.
Let’s say that we have the following HTML where we want to give the user the ability to remove a div #div4. The div will just be a greenish box with set dimensions.
Here is the HTML code:
Remove box above
In the JavaScript code, we will add an onclick event to a button that will run a function we will create. In the function, we will simply call the remove() method on the div which will remove it from the DOM.
Here is the JavaScript code:
function removeDiv(){
document.getElementById("div4").remove();
};
The final code and output for this example of removing an Element using JavaScript with a click is below:
Code Output:
Full Code:
Remove box above
Hopefully this article has been useful for you to understand how to use JavaScript to remove an element from the DOM.