0

Im just wondering in order to remove a parent, you need to go to its parentNode. such as:

 div.parentNode.removeChild(div);

What happens if div has no parents? How can you remove div without going to its parents?

melpomene
  • 84,125
  • 8
  • 85
  • 148
  • 4
    Every `
    ` will have at least on parent: ``
    – Randy Casburn Apr 20 '18 at 14:27
  • True that, but I was just wondering if in some weird case it doesnt. or say you want to remove how would you do that? –  Apr 20 '18 at 14:28
  • 1
    @RandyCasburn, really, every element will have at least one parent: ``. – zero298 Apr 20 '18 at 14:29
  • 1
    There _is_ an element [`.remove`](https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove) method, but it has zero IE support. Check [here](https://stackoverflow.com/questions/8830839/javascript-dom-remove-element) – Alexander Nied Apr 20 '18 at 14:29
  • 1
    @zero298 - you are incorrect my friend. Every browser will automatically insert the `` element if an errant developer does not do it themselves. This is much like when every `` has a `` element whether you put it there or not.
    – Randy Casburn Apr 20 '18 at 14:31
  • 1
    @RandyCasburn Interesting, and `document.getElementsByTagName("body")[0].parent;` returns `undefined`. Good note. – zero298 Apr 20 '18 at 14:33
  • @zero298 - That was not the OPs question. the question was about a '
    ' not the document body - stop being obtuse.
    – Randy Casburn Apr 20 '18 at 14:33

2 Answers2

0

If a div element doesn't have parent, there is no place to remove this div from, so your div element doesn't exist in the page. It's safe to use div.parentNode.removeChild(div); because if the div element doesn't have a parent, it is already removed, or just never added to the page.

melpomene
  • 84,125
  • 8
  • 85
  • 148
Dahou
  • 522
  • 4
  • 12
0

No need to go to the parent. Just use remove.

div.remove();

That will remove the exact node.

This is not supported in older browsers so you would need a polyfill for them as defined on this page: http://devdocs.io/dom/childnode/remove

Intervalia
  • 10,248
  • 2
  • 30
  • 60