Some time ago I was wondering the following question:
What is the difference between:
-
$(document.body)
-
$('body')
If you could justify me, it would be very helpful.
Some time ago I was wondering the following question:
What is the difference between:
$(document.body)
$('body')
If you could justify me, it would be very helpful.
When you make the reference to $(document.body)
deliver the BODY element directly to the jquery. Whereas when you do $('body')
jquery you have 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. Referring by document
you refer directly to the element within the DOM while using the $('body')
selector, JQuery will have to interpret that it is the <body>
tag that is inside the page and therefore this second selector will be more slow.
As they put you in other answers: the final result will be the same (the element body
will be selected) and one of the options ( document.body
) will be faster than the other ( "body"
).
If we get a little fussy, there is a small difference in old versions of jQuery: the context that was passed and in which the jQuery code was executed.
.context
is available in jQuery 1.x (from 1.3) and 2.x, marked as obsolete in version 1.10, and was completely eliminated in version 3.0. With this method you can see the context of the DOM node that was originally passed to jQuery()
; if none is passed, then the context is surely document
.
If .context
were used, there would be a difference between doing $(document.body)
and $("body")
, because the context would be body
and #document
respectively and they are not the same (eg you can add elements to body
but not document
).
Example using context
with $(document.body)
:
var body = $(document.body);
var h1 = $("<h1>Encabezado</h1>")[0];
body.context.append(h1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Example using context
with $("body")
:
var body = $("body");
var h1 = $("<h1>Encabezado</h1>")[0];
body.context.append(h1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>