Fakhrane Nassiry
Fakhrane Nassiry

Reputation: 645

How to check if an element exists in DOM or not in JavaScript

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.

Upvotes: 0

Views: 778

Answers (3)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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.

Upvotes: 4

CoderPi
CoderPi

Reputation: 13211

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>

Upvotes: 1

MinusFour
MinusFour

Reputation: 14423

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>

Upvotes: 3

Related Questions