Is it possible to remove/delete an HTML element from the markup directly using Javascript/jQuery/Ajax instead of using CSS display: none?
-
4Just being a bit pedantic, but you're not exactly removing it from the markup - you're removing it from the Document Object Model. Markup is just the text transmitted over the wire.Neall– Neall2011-04-29 16:15:12 +00:00Commented Apr 29, 2011 at 16:15
Add a comment
|
5 Answers
Yes
JavaScript
var parent = document.getElementById('parentElementID');
var child = document.getElementById('childElementID');
parent.removeChild(child);
jQuery
$('#parentElementID').remove('#childElementID');
4 Comments
kapa
or even easier
$('#childElementId').remove()Dustin Laine
Agree, wanted to be more descriptive. Always suggest refactoring as much as possible.
Andreas
or with "vanilla" js and without the need to "know" the parent element
child.parentNode.removeChild(child)ClosDesign
I know this is from a while back and now there is a new .remove() for Vanilla JS that does not work on IE, so the remove .removeChild() is the best cross browser. And I know there is a campaign the shite on jQuery lately for not being good enough or a hindrance, but jQuery just makes it easy. Plan and simple.
This is an old question, so the answers are somewhat dated. It used to be that to remove an element, you got the parent node, the element, and use removeChild(), as other suggested:
element.parentNode.removeChild(element);
While this is still perfectly acceptable, you can now remove the node directly:
document.getElementById('elementId').remove();
document.getElementById('remove-button').addEventListener('click', function() {
document.getElementById('container').remove();
});
#container {
width:50px;
height:50px;
background-color:#bada55;
}
<div id="container"></div>
<button id="remove-button">Remove</button>
1 Comment
ClosDesign
I know this is from a while back and now there is a new .remove() for Vanilla JS and I agree with this answer and up-voted it, and that does not work on IE, so the .removeChild() is the best cross browser if you are still supporting IE for one reason or another. And I know there is a campaign the shite on jQuery lately for not being good enough or a hindrance, but jQuery just makes it easy for cross browser support. Thanks for updating the answer too.