3

Is it possible to remove/delete an HTML element from the markup directly using Javascript/jQuery/Ajax instead of using CSS display: none?

1
  • 4
    Just 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. Commented Apr 29, 2011 at 16:15

5 Answers 5

11

Yes

JavaScript

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

jQuery

$('#parentElementID').remove('#childElementID');
Sign up to request clarification or add additional context in comments.

4 Comments

or even easier $('#childElementId').remove()
Agree, wanted to be more descriptive. Always suggest refactoring as much as possible.
or with "vanilla" js and without the need to "know" the parent element child.parentNode.removeChild(child)
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.
7
element.parentNode.removeChild(element)

Comments

3

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

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.
2

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

Comments

2

native javascript:

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

Or in jquery just use

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.