简体   繁体   中英

Check if JQuery object exists in DOM

I have a function which expect from parameter JQuery object. I need to find if JQuery object exists in DOM or not (in $('<div></div>') case).

I check for duplicates and found several answers ( link1 , link2 , link3 ). Can some expert shine some light witch is the best (fastest) way to do it.

Options are:

$.contains //not working
$a.find
$a.parent()
$a.closes()
document.contains()
$a[0].isConnected  

Snippet:

 var a = $("#test"); //length 1 var b = $('<div></div>'); //length 1 console.log("contains: ", $.contains(document, a), $.contains(document, b)); //false, false console.log("find: ", !!$(document).find(a).length, !!$(document).find(b).length); // true, false console.log("parent: ", !!a.parent().length, !!b.parent().length); // true, false console.log("closest: ", !!a.closest('body').length, !!b.closest('body').length); //true, false console.log("document.contains: ", document.contains(a[0]), document.contains(b[0])); //true, false console.log("isConnected: ", a[0].isConnected, b[0].isConnected); //true, false 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> </head> <body> <div id="test"></div> </body> </html> 

Thank you.

If performance is a really big concern for you, native methods are generally the way to go.

document.contains($myJQueryEl[0])

Outperforms the next fastest jQuery operation, $elem.closest('body') , by around 4 times according to this answer and its comment .

If you're really looking for performance for non-document elements, however, Shadow DOM is definitely your best option.

Do not use jQuery if you want best performance. You can try isConnected :

The isConnected attribute's getter must return true, if context object is connected , and false otherwise.

An element is connected if its shadow-including root is a document .

$element[0].isConnected; // jQuery
element.isConnected; // Native JS

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