How to remove an HTML element from a web page using JavaScript?

To remove an HTML element from a web page using JavaScript, you can use various methods depending on the situation:

  1. Remove element by ID: If the element has an ID attribute, you can use the getElementById() method and then remove it using the remove() method.
var element = document.getElementById("element-id"); element.remove();
  1. Remove element by class name: If the element has a specific class name, you can use the getElementsByClassName() method to get all the elements with that class, and then remove them individually using a loop and the remove() method.
var elements = document.getElementsByClassName("element-class"); for (var i = 0; i < elements.length; i++) { elements[i].remove(); }
  1. Remove element by tag name: If you want to remove all elements of a specific tag name, you can use the getElementsByTagName() method to get all the elements with that tag, and then remove them individually using a loop and the remove() method.
var elements = document.getElementsByTagName("element-tag"); for (var i = 0; i < elements.length; i++) { elements[i].remove(); }
  1. Remove element using parent element: If you have access to the parent element of the element you want to remove, you can use the removeChild() method to remove it.
var parentElement = document.getElementById("parent-element-id"); var elementToRemove = document.getElementById("element-id"); parentElement.removeChild(elementToRemove);

Note: The remove() method is not supported in Internet Explorer. In this case, you can use the parentNode property to access the parent element and then remove the target element using the removeChild() method.