How to Remove Element in Javascript
In this tutorial, you will learn how to remove element in javascript. This is something that comes under DOM manipulation and is one of the skills that you must have if you want to be a good javascript developer.
Every element in javascript has a parent element and if you have access to the parent element, then you can make use of removeChild()
method to remove any child element. This method works great if you want to remove a specific child element, but what if you want to get rid of all the child elements in one go. In such a scenario, you can make use of the innerHTML
property and set it to an empty string.
We will cover both of the methods mentioned above in this tutorial. In the following example, we have a bunch of li
elements and upon click of a button, we will remove all of them. Please have a look over the code example and the steps given below.
HTML & CSS
- We have 4 elements in the HTML file (
div
,button
,ul
, andli
). Thediv
element is just a wrapper for the rest of the elements. - The inner text for the
button
element is“Remove”
. - We have a bunch of fruit names in the
ul
element. - We have done some basic styling using CSS and added the link to our
style.css
stylesheet inside thehead
element. - We have also included our javascript file
script.js
with ascript
tag at the bottom.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="style.css"> <title>Document</title> </head> <body> <div> <button>Remove</button> <ul> <li>Mango</li> <li>Grapes</li> <li>Kiwi</li> <li>Apple</li> </ul> </div> <script src="script.js"></script> </body> </html>
div { width: 250px; margin: auto; } button{ margin-left: 20px; } li{ font-size: 20px; }
Javascript
- We have selected 2 elements
button
andul
using thedocument.querySelector()
method and stored them inbtnRemove
andparent
variables respectively. - We have selected all the
li
elements using thedocument.querySelectorAll()
method and stored them infruits
variable. - We have attached the
click
event listener to thebutton
element. - In the event handler function, we are looping through all the
li
elements usingfor
loop. Inside the loop, we are calling theremoveChild()
method of theul
element and passing eachli
element as a parameter. This is the first way of removing all theli
elements. - The second way of removing all the
li
elements is to use theinnerHTML
property of theul
element and set it to an empty string.
let btnRemove = document.querySelector('button'); let parent = document.querySelector('ul'); let fruits = document.querySelectorAll('li'); btnRemove.addEventListener('click', () => { /* for(fruit of fruits){ parent.removeChild(fruit); } */ parent.innerHTML = ''; });