Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$(document) vs. $("document")

Is there any difference between: $(document) and $("document")?

EDIT: also when into the .ready() e.g. $("document").ready()

like image 700
MacMac Avatar asked Jan 24 '11 18:01

MacMac


1 Answers

$(document) uses jQuery to wrap the global document object.

$("document") attempts to look for a <document> element, which obviously makes no sense in HTML because there's no such element, only a root document object represented in the markup by the <html> element. It behaves that way because by passing the jQuery function a string, you're actually giving it a selector.

Re edit: as patrick dw says, in the context of ready() there's no difference, and in fact as of jQuery 3.0 using $(document) at all or explicitly calling ready() is deprecated. From the documentation:

jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:

  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the .ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior. For example, the third syntax works with "document" which selects nothing. The fourth syntax waits for the document to be ready but implies (incorrectly) that it waits for images to become ready.

like image 153
BoltClock Avatar answered Oct 05 '22 03:10

BoltClock