开发者

Is there a way to completely remove an HTML element using Javascript?

Is it possible to remove/delete a开发者_StackOverflow社区n HTML element from the markup directly using Javascript/jQuery/Ajax instead of using CSS display: none?


Yes

JavaScript

var parent = document.getElementById('parentElementID');
var child = document.getElementById('childElementID');
parent.removeChild(child);

jQuery

$('#parentElementID').remove('#childElementID');


element.parentNode.removeChild(element)


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>


Yes. You could use the jQuery remove() API.


native javascript:

    var toremove = document.getElementById('hd');
    toremove.parentNode.removeChild(toremove);

Or in jquery just use

$('#toremove').remove();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜