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?
$(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:
It's longer to write and more awkward to read, inflating your script size
It results in more memory churn (more temporary objects get created/destroyed)
It's slower - http://jsperf.com/vs-document-find, http://jsperf.com/selector-vs-find-again
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 div
s 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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With