JavaScript: What is the difference between “Document” and “HTML”?

Example:

$(document).click(function() { blah }); // and $('html').click(function() { blah }); 
+7
javascript jquery
source share
4 answers

I will answer the question in several parts.

In JavaScript (not just jQuery, but all JavaScript), the document keyword is a handle to an object that contains an HTMLDocument. You can use this descriptor in the following scripts ...

 // Get the current web address alert(document.location.href); 

When you pass a document to jQuery, it parses the document into a jQuery object.

When you pass the "html" selector to jQuery, it uses this string to search for any elements in the document object model that match the selector (in all cases there will be one html element).

In fact, you will not notice the difference in behavior between them:

 $(document).click(function() { alert('blah'); }); $('html').click(function() { alert('blah'); }); $('body').click(function() { alert('blah'); }); 

But the technical difference is that the document is an object, and "html" is a string that is used to search for an element. Both the object and any corresponding elements are converted to jQuery objects.

Because they all add a click event handler to the "visible" part of the page, which is the only part of the page that the user can actually click on.

+12
source share

try to output innerHTML of both, what is the result? I believe (but did not verify) that

  • document is a truly complete document, including <html> and all its elements
  • html refers to <html> -tag, so in your output there will be only <head> and <body> , not <html> -tag

but: for your code (adding a click handler) there would be no difference, because a click in a document will always be a click on <html> (as long as your site is valid and has <html> -tag)

+1
source share

They choose the same thing. The only difference is how the jQuery sizzle engine finds it. The first case is a special case in the jQuery initialization function, the second is using getElementsByTagName

+1
source share

I noticed a few differences:

  1. document is a DOM Element which wraps the HTML - DOM Element whereas html is an HTML DOM element .
  2. document includes the first line of the document — the one that indicates doctype . For example <!doctype html> (for HTML 5)
  3. HTML can have class, id and other attributes whereas document does not (and cannot have) these attributes . Try $(document).addClass('test') v/s $('html').addClass('test'); and notice the difference in the elements tab on developer console .

Good luck ...

0
source share

All Articles