简体   繁体   中英

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

Is it possible to remove/delete an 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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM