2

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.

Community
  • 1
  • 1
Makla
  • 9,899
  • 16
  • 72
  • 142

2 Answers2

3

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.

Community
  • 1
  • 1
Jack Guy
  • 8,346
  • 8
  • 55
  • 86
  • 1
    @Makla you didn't mention browser compatibility as one of your requirements. If that's the case, then as I said above `$elem.closest('body')` is the next-fastest alternative. :) – Jack Guy Aug 03 '16 at 20:29
2

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
Oriol
  • 274,082
  • 63
  • 437
  • 513