0

I removed an element from DOM with this code :

box1.parentNode.removeChild(box1);

How can I check if box1 is in the DOM or not.

I want this because if I'll try to remove it from the DOM again, this will cause an error.

6
  • could you please make your question more clear? (i was not downvoting) Commented Dec 20, 2015 at 17:48
  • 1
    Why downvoting? His questions looks clear to me even the English if the english is not great. if (box1) { box1.parentNode.removeChild(box1); } ? Commented Dec 20, 2015 at 17:49
  • Can you provide proper details? Commented Dec 20, 2015 at 17:49
  • 1
    Possible duplicate of How to find with javascript if element exists in DOM or it's virtual (has been just created by createElement) Commented Dec 20, 2015 at 17:50
  • Down voting because OP haven't tried Googling. Commented Dec 20, 2015 at 17:52

3 Answers 3

4

The Node.contains() method returns a Boolean value indicating whether a node is a descendant of a given node or not.

You can use Contain :

if( node.contains( otherNode ) ){
    //Your code here
}

NOTE : To check in all the DOM use document.contains(node).

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

3

You can just use the parentNode property to see if the node is attached.

var div = document.querySelector('div');
console.log(div.parentNode !== null); //Attached, true
div.parentNode.removeChild(div);
console.log(div.parentNode !== null); //Not attached, false
<div></div>

Comments

1

var box1 = document.getElementById("box1") // EXAMPLE to get an element

if (box1.parentNode && box1.parentNode.contains(box1)) {
  box1.parentNode.removeChild(box1);
}

// Example: won't trigger an error:
if (box1.parentNode && box1.parentNode.contains(box1)) {
  box1.parentNode.removeChild(box1);
}

// Example: would trigger an error:
box1.parentNode.removeChild(box1);
<div id="box1">a</div>
<div id="box2">b</div>
<div id="box3">c</div>

6 Comments

What happens if box1 is null?
it can't be null, we set it to hold an element. But it might not have an parentElement in the DOM when it's not in the dom (anymore), thats why it checks for parentNode but not for box1 itself
I meant if box1 element was not in DOM, wouldn't document.getElementById("box1") return null?
:D I saw your answer, and be assured I did not downvote it. But document.getElementById("box1") is just an example 😉 to get an Element
No worries. I was trying to check whether you should be using box1 && box1.parentNode...
|

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.