Search code examples
javascriptdomwindowdocument

Will `document.appendChild()` reload all the html page?


Will document.appendChild(xxx) reload all the html page?

I have two questions there:

  1. when I use document's function, will all the html page be reloaded?
  2. whether window object belong to JavaScript? and whether JavaScript method to change part of a html page, all the page will reload?

Solution

  • You can't use document.appendChild() actually because the document can only have one element. For example, if you open up the browser console in your browser and try to run:

    document.appendChild(document.createElement('span'));
    

    It will throw an error:

    VM912:1 Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed.
    

    However, you can append children to other DOM nodes such as the body

    document.body.appendChild(document.createElement('span'));
    

    will append a new node to the body tag. It will not reload the entire page. If you run that in the browser console and then look at the HTML Elements of your page, you will see that there is now an empty <span> before the closing </body> tag.

    For documentation on all those javascript APIS, check out https://developer.mozilla.org.