Search code examples
javascriptnodesremovechild

How to check if node have childNode before removing it?


I just got this weird error:

enter image description here

And I don't know how that happened.
.contains() should return true only if placeholder is a child of overParent, but how can that return true and dont have placeholder as it's child?

Solutions I need:

  1. Why and How this error is happening?
  2. A better solution to remove placheholder only when it's a child of overParent.

Observations:

I'm doing this on react.


Solution

  • Problem is, although .contains tells you that placeholder is a descendant of overParent, it can be a grandchild node. If that's the case, you are trying to remove a node which is in another node from overParent.

    For demonstration purposes, check if the actual DOM looks like this:

    - overParent
        - <some node>
           - placeholder
    

    To avoid errors like this, go to the direct parent of the node you want to remove and call removeChild on it instead:

    if (overParent.contains(placeholder)) {
        placeholder.parentNode.removeChild(placeholder);
        // rest of your code
    }