1var colors = ["red","blue","car","green"];
2var carIndex = colors.indexOf("car");//get "car" index
3//remove car from the colors array
4colors.splice(carIndex, 1); // colors = ["red","blue","green"]
1Removing an element is much easier, as it only requires the element's ID.
21. function removeElement(elementId) {
32. // Removes an element from the document.
43. var element = document. getElementById(elementId);
54. element. parentNode. removeChild(element);
65. }
7
8Example:
9<h1>The remove() Method</h1>
10
11<p>The remove() method removes the element from the DOM.</p>
12
13<p id="demo">Click the button, and this paragraph will be removed from the DOM.</p>
14
15<button onclick="myFunction()">Remove paragraph</button>
16
17<script>
18function myFunction() {
19 var myobj = document.getElementById("demo");
20 myobj.remove();
21}
22</script>
1// Get the element you want to remove
2var element = document.getElementById(elementId);
3
4// Get the parent and remove the element since it is a child of the parent
5element.parentNode.removeChild(element);
1<div id="div-01">Here is div-01</div>
2<div id="div-02">Here is div-02</div>
3<div id="div-03">Here is div-03</div>
4