3

What is actually the difference between document and document.body?

For example, I have the following code:

document.addEventListener('click',function(){ 
document.write('You click me!') 
})
<div>Click anywhere</div>

What will be the difference if I use document.body instead of document ?

And what is actually the difference between document and document.body?

I tried to search online, but couldn't find any useful information.

Thanks for any responds!

James
  • 2,732
  • 2
  • 5
  • 28
  • 1
    See [Difference between document.addEventListener and window.addEventListener?](/q/12045440/4642212). The effect of binding the listener on either target is almost the same. The difference is noticable if the `` doesn’t cover the entire height of the page. Otherwise the difference between an [`HTMLDocument`](//developer.mozilla.org/docs/Web/API/HTMLDocument) and an [`HTMLBodyElement`](//developer.mozilla.org/docs/Web/API/HTMLBodyElement) is significant. The recommended call is probably just `addEventListener("click", () => console.log("You clicked me!"));`. Don’t use `document.write`. – Sebastian Simon Dec 25 '21 at 01:25
  • You should probably read up on what the Document Object Model (DOM) is all about also – charlietfl Dec 25 '21 at 01:53

1 Answers1

0

The document will have all the information of your entire HTML of a page.

The document.body will refer to your HTML Body.

See the difference

  • 1
    Document isn't just the HTML. There is a whole context and API for interactivity, location, etc. https://developer.mozilla.org/en-US/docs/Web/API/Document – Brad Dec 26 '21 at 23:29