Syntax error How to remove elements using the splice() method in JavaScript?

How to remove elements using the splice() method in JavaScript?



Following is the code for removing elements using splice() method in 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;
   }
   .sample,.result {
      font-size: 20px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Remove elements using splice()</h1>
<div class="sample"></div>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to remove elements between 1st and 5th element</h3>
<script>
   let fillEle = document.querySelector(".sample");
   let resEle = document.querySelector(".result");
   let arr = [1, 3, 5, 7, 9, 11];
   fillEle.innerHTML = arr;
   document.querySelector(".Btn").addEventListener("click", () => {
      arr.splice(1, 4);
      resEle.innerHTML = "Spliced array = " + arr;
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 2020-07-16T08:11:26+05:30

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements