remove child node of a specific element in JavaScript?


To remove the child node of a list javascript has provided removeChild() method. Using this method we can remove any list item using its index position. Let's discuss it in a nutshell.

syntax

node.removeChild(node);

Example-1

In the following example, there are 3 elements in the provided list but after removing a child there are only two elements in the list and they were displayed in the output.  

Live Demo

<html>
<body>
<ul id = "list"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul>
<script>
   var list = document.getElementById("list");
   list.removeChild(list.childNodes[1]);
</script>
</body>
</html>

Output

Tesla
Solarcity


Example-2

In the following example, there are 3 elements in the provided list but after removing the first child using method removeChild() the other remaining two elements left were displayed as shown in the output.  

Live Demo

<html>
<body>
<ul id = "list"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul>
<script>
   var list = document.getElementById("list");
   list.removeChild(list.childNodes[0]);
</script>
</body>
</html>

Output

Spacex
Solarcity
raja
Published on 09-Aug-2019 16:09:39
Advertisements