Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

I've started working on some project and in code I find combintions of $(document).find('selector') and $('selector'). I cant find any real reason why this is done. I there any significant differnece between those two so that they are used simultaneously in project? should I prefer one before another in some cases?

like image 218
Olena Horal Avatar asked Dec 16 '14 10:12

Olena Horal


1 Answers

$(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).

like image 128
T.J. Crowder Avatar answered Sep 20 '22 16:09

T.J. Crowder