document. body is the element that contains the content for the document. In documents with <body> contents, returns the <body> element, and in frameset documents, this returns the outermost <frameset> element.
You can only replace the HTML's body element with PHP if you are outputting the HTML with PHP (changing it before outputting it). PHP works server-side, so once the HTML reaches the client it cannot modify it.
body object, it is most likely because the body has not been defined yet. If document. body is null, you most likely need to execute your code in the window. onload function.
body. className = ''; This will change the contents of the class attribute to be the empty string, so it will remove all the classes the element might have.
They refer to the same element, the difference is that when you say document.body
you are passing the element directly to jQuery. Alternatively, when you pass the string 'body'
, the jQuery selector engine has to interpret the string to figure out what element(s) it refers to.
In practice either will get the job done.
If you are interested, there is more information in the documentation for the jQuery function.
The answers here are not actually completely correct. Close, but there's an edge case.
The difference is that $('body') actually selects the element by the tag name, whereas document.body references the direct object on the document.
That means if you (or a rogue script) overwrites the document.body element (shame!) $('body') will still work, but $(document.body) will not. So by definition they're not equivalent.
I'd venture to guess there are other edge cases (such as globally id'ed elements in IE) that would also trigger what amounts to an overwritten body element on the document object, and the same situation would apply.
I have found a pretty big difference in timing when testing in my browser.
I used the following script:
WARNING: running this will freeze your browser a bit, might even crash it.
var n = 10000000, i;
i = n;
console.time('selector');
while (i --> 0){
$("body");
}
console.timeEnd('selector');
i = n;
console.time('element');
while (i --> 0){
$(document.body);
}
console.timeEnd('element');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I did 10 million interactions, and those were the results (Chrome 65):
selector: 19591.97509765625ms
element: 4947.8759765625ms
Passing the element directly is around 4 times faster than passing the selector.
$(document.body)
is using the global reference document
to get a reference to the body
, whereas $('body')
is a selector in which jQuery will get the reference to the <body>
element on the document
.
No major difference that I can see, not any noticeable performance gain from one to the other.
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