To remove an HTML element from a web page using JavaScript, you can use various methods depending on the situation:
getElementById()
method and then remove it using the remove()
method.var element = document.getElementById("element-id");
element.remove();
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();
}
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();
}
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.