[removed] Whats the difference between 'Document' and 'HTML'

后端 未结 4 1533
一整个雨季
一整个雨季 2021-01-02 16:26

Example:

$(document).click(function() { blah });   
// and
$(\'html\').click(function() { blah });
相关标签:
4条回答
  • 2021-01-02 16:38

    A few differences I noticed are:

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

    Good Luck...

    0 讨论(0)
  • 2021-01-02 16:41

    They select the same thing. The only difference is how jQuery's sizzle engine finds it. The first case being a special case in the jQuery init function, the second one using the getElementsByTagName

    0 讨论(0)
  • 2021-01-02 16:47

    try to put out the innerHTML of both, whats the result? i reckon (but han't tested) that

    • document is really the complete document, including <html> and all elements in it
    • html references the <html>-tag, so there will only be the <head> and <body> in your output, not the <html>-tag itself

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

    0 讨论(0)
  • 2021-01-02 16:52

    I'll answer the question in several parts.

    In JavaScript (not just jQuery, but all JavaScript) the document keyword is a handle on the object that contains the HTMLDocument. You might use this handle in the following scenarios...

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

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

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

    In reality, you won't notice a difference in behaviour between these:

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

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

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

    0 讨论(0)
提交回复
热议问题