is there $(document).find('selector') and $('selector') difference

$(document).find("selector") and $("selector") will match the same set of elements.

There's no reason to use $(document).find("selector") over just $("selector") (unless the selector you're using comes from an untrusted source — more on that in a moment), and several reasons not to:

  1. It's longer to write and more awkward to read, inflating your script size

  2. It results in more memory churn (more temporary objects get created/destroyed)

  3. It's slower - http://jsperf.com/vs-document-find, http://jsperf.com/selector-vs-find-again

enter image description here

However, if you have $(selector) where selector comes from an untrusted source, beware that jQuery sniffs the string and either does a selection or creates new HTML elements. That is, $("div") looks for divs but $("<div>") creates a div. If the text you're using comes from an untrusted source, it could be <script src='http://example.com/path/to/malicious/script.js>. Now, in and of itself that wouldn't be a problem, but if the resulting script element is added to a document (for instance, $(selector).appendTo(document.body)), suddenly it's an XSS attack vector. Likely? No, if you're selecting you aren't that likely to then append (though you might, if you're moving elements). But if the selector comes from an untrusted source, $(document).find(selector) ensures that the text is only used as a selector, not as an HTML string. Or, on a modern browser, $(document.querySelectorAll(selector)) (but you can't use jQuery's extensions to selectors that way).


They're functionally equivalent. There is no difference in behavior between $("selector"), $(document).find("selector") and $("selector", document).

As for performance, some of the variants may be slightly slower than the others (since these methods are implemented in terms of the others). This is, however, an implementation detail and is subject to change between releases. Benchmarking a specific release would tell for sure.


Exact answer to the question is 'yes there is difference between both' even though both do the same job of pointing / selecting the element.

When document is loaded, jQuery scope gets defined. Thus usually $('selector') is used to point the element.

But what if elements are added after this scope is defined. I.e. If elements are loaded through ajax call. jQuery can't find these elements. Thus to point to such elements we use alternative function $('scope').find('selector').

Best-practice: if you don't add elements after document is loaded. Don't use "$('scope').find('selector')" method. As the given name will be considered as criteria and according to the find function, every element will be checked to match the criteria which will consume more time and will demand more resource than directly pointing method.

Tags:

Jquery