-2

I am having trouble using parent.removeChild(). I think I am using the correct syntax. Does anyone know what is wrong?

var parent = document.body
var child = document.getElementById("clueDiv")
parent.removeChild(child);
Charlie S
  • 1
  • 1
  • 1
    If that's not working, probably is because "clueDiv" is not a direct child of "document.body" – nanocv Dec 12 '15 at 23:22

2 Answers2

2

If that does not work, probably child is not child of document.body.

Try with:

child.parentElement.removeChild(child)

Or, as @PaulS. said:

child.parentNode.removeChild(child)
zvone
  • 18,045
  • 3
  • 49
  • 77
  • Why `.parentElement` and not `.parentNode`? – Paul S. Dec 12 '15 at 23:23
  • Wow, I wrote the same at the same time in the comments of the question. Upvote ;) – nanocv Dec 12 '15 at 23:25
  • @PaulS. I've never seen a case when they are not the same ;) Anyway, I guess `parentNode` probably does work in more cases. – zvone Dec 12 '15 at 23:26
  • BTW, a link for the curious: http://stackoverflow.com/questions/8685739/difference-between-dom-parentnode-and-parentelement – zvone Dec 12 '15 at 23:32
  • 1
    @zvone Most often you'd encounter differences when you reach non-Element nodes such as a _#document-fragment_ or _#document_ at the top of the DOM tree, where `.parentElement` becomes `null` but you could still append and remove child nodes to these objects. – Paul S. Dec 13 '15 at 02:52
1

You can also use ChildNode.remove():

var child = document.getElementById("clueDiv");
child.remove();

It's not supported in Internet Explorer, but you can use a polyfill:

if (!('remove' in Element.prototype)) {
    Element.prototype.remove = function() {
        if (this.parentNode) {
            this.parentNode.removeChild(this);
        }
    };
}
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
  • 1
    I wanted to warn this was defined in a draft. But wow, DOM4 is already a recommendation! – Oriol Dec 13 '15 at 00:06