How can I remove a child node in HTML using JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to remove a child node in HTML using JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Removing a child node in HTML using JavaScript</h1>
<div style="color: green;" class="result">
<ul class="animal">
<li>Cow</li>
<li>Lion</li>
<li>Tiger</li>
<li>Buffalo</li>
</ul>
</div>
<button class="Btn">CLICK HERE</button>
<h3>
Click the above button to remove the first list element from the above
list
</h3>
<script>
   let resEle = document.querySelector(".result");
   let animalList = document.querySelector(".animal");
   document.querySelector(".Btn").addEventListener("click", () => {
      animalList.removeChild(animalList.childNodes[0]);
      animalList = animalList;
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

raja
Published on 17-Jul-2020 12:28:22
Advertisements