简体   繁体   中英

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.

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.

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>

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM