Kodeclik Blog
Removing Elements from a DOM in Javascript
We will learn how to use Javascript to programmatically remove elements from the DOM of a webpage. To explore this operator, we will write and embed our Javascript code inside a HTML page like so:
In the above HTML page you see the basic elements of the page like the head element containing the title (“Javascript remove element from DOM”) and a body with an empty script tag. Any HTML markup goes inside the body tags and any Javascript code goes inside the script tags.
Let us create a very simple webpage listing some basic information:
The underlying source is:
Let us suppose now that our objective is to remove the Minecraft element (programmatically). To accomplish this we need to be able to somehow refer to this element inside the program. For this purpose we can give name tags to the individual list items the “li” elements).
The output is (still):
Let us now write some Javascript code to identify a specific element (in our case, the Minecraft element) and remove it. Here is the code to precisely that:
As you can see we first use the querySelector method on the document (which is the full webpage) to look for elements whose name is Minecraft. There is only one such element in our case. Then in the second line of Javascript we apply the remove() method on this element which will remove it from the DOM tree. If we do this, the output will be:
There are many ways to refer to elements. For instance you can refer to them by their id using the getElementById() method. We will use this to remove the second (now the first) element:
The output is now:
We could have used the earlier querySelector method as well to obtain the same effect:
The output will be the same as before, giving Fortnite as the only remaining result.
There are more complex selectors we can use to identify and remove elements which is beyond the scope of this blogpost. But you now have a very good understanding of the basic concepts behind removing elements from a DOM programmatically. Enjoy!
Interested in learning more Javascript? Learn how to loop through two Javascript arrays in coordination and how to make a Javascript function return multiple values!
Want to learn Javascript with us? Sign up for 1:1 or small group classes.