From 1b0d12b66409d5c8a5790dc171304cdee2f6438e Mon Sep 17 00:00:00 2001 From: Kirill Berezin Date: Sat, 3 Sep 2016 12:36:10 +0300 Subject: [PATCH] Explain how to test if element attached to main DOM --- .../faq/how-do-i-test-whether-an-element-exists.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/page/using-jquery-core/faq/how-do-i-test-whether-an-element-exists.md b/page/using-jquery-core/faq/how-do-i-test-whether-an-element-exists.md index c6ef018e..d1a40e0c 100644 --- a/page/using-jquery-core/faq/how-do-i-test-whether-an-element-exists.md +++ b/page/using-jquery-core/faq/how-do-i-test-whether-an-element-exists.md @@ -17,3 +17,14 @@ Note that it isn't always necessary to test whether an element exists. The follo ``` $( "#myDiv" ).show(); ``` + +If you need to understand if element is present in main DOM tree, or if you're previously stored selector set in variable, use [jQuery.contains](https://api.jquery.com/jQuery.contains/) + +``` +var elements = $('#myDiv'); +if ($.contains(document, elements)) { + elements.show(); +} +``` + +Because modern browsers detaching elements in [DocumentFragment](https://developer.mozilla.org/ru/docs/Web/API/Document/createDocumentFragment), `.length` will always return constant value, even if element already removed from page.