To remove an HTML element using JavaScript, you can use the remove()
method or parentNode.removeChild()
method.
To do this, we write:
Using remove()
method:
// Assuming you have a reference to the element you want to remove
var elementToRemove = document.getElementById('elementId');
elementToRemove.remove();
Using parentNode.removeChild()
method:
// Assuming you have a reference to the parent element and the element you want to remove
var parentElement = document.getElementById('parentElementId');
var elementToRemove = document.getElementById('elementId');
parentElement.removeChild(elementToRemove);
In both examples, document.getElementById('elementId')
is used to select the element you want to remove.
You can replace 'elementId'
with the actual ID of the element you want to remove.
Then, you either call remove()
directly on the element reference or use parentNode.removeChild()
on the parent element, passing the element reference you want to remove as an argument.
Choose the method that suits your needs or preferences. Both achieve the same result.