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.
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.
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>
box1 is null?box1 element was not in DOM, wouldn't document.getElementById("box1") return null?document.getElementById("box1") is just an example 😉 to get an Elementbox1 && box1.parentNode...
if (box1) { box1.parentNode.removeChild(box1); }?