Some time ago I was wondering the following question:
What is the difference between:
$(document.body)
$('body')
If you could explain me, it would be of great help.
Some time ago I was wondering the following question:
What is the difference between:
$(document.body)
$('body')
If you could explain me, it would be of great help.
When you reference a you
$(document.body)
directly hand over the BODY element to the jquery. Whereas when you do$('body')
jquery it has to search and interpret the string (in this case body) and find the element.Some websites explain how the response performance changes in different cases.
Having the fastest performance using
$(document.body)
and the slowest$('body)
here you can find some examples
They really are the same. By referencing via
document
you directly reference the element within the DOM while using the selector$('body')
, JQuery will have to interpret that it is the tag<body>
inside the page and therefore this second selector will be slower.As they tell you in other answers: the final result will be the same (the element will be selected
body
) and one of the options (document.body
) will be faster than the other ("body"
).If we're getting a little fussy, there is one small difference in older versions of jQuery: the context that was passed and in which the jQuery code was executed.
.context
is available in jQuery 1.x (as of 1.3) and 2.x, was deprecated in version 1.10, and was completely removed in version 3.0. With that method you can see the context of the DOM node that was originally passed tojQuery()
; if neither is passed, then the context is likely to bedocument
.If used
.context
, there would be a difference between doing$(document.body)
and$("body")
, because the context would bebody
and#document
respectively and they are not the same (eg you can add elements tobody
but not todocument
).Example using
context
with$(document.body)
:Example using
context
with$("body")
: