The DOM and JavaScript

We'll dive deeper into the DOM by discussing DOM data types and the properties and methods used to access DOM elements using JavaScript. 

Read this article and locate the methods used with the "window" and "document" objects. For example, when a program uses an alert, it uses the "window.alert" method. JavaScript uses the "window.onload" method when a page is loaded. When a user clicks an element on a page, the "onclick" method is called. Remember that calling a method for an object uses dot (.) notation.

You don't have to do anything special to begin using the DOM. You use the API directly in JavaScript from within what is called a script, a program run by a browser.

When you create a script, whether inline in a <script> element or included in the web page, you can immediately begin using the API for the document or  window objects to manipulate the document itself, or any of the various elements in the web page (the descendant elements of the document). Your DOM programming may be something as simple as the following example, which displays a message on the console by using the console.log() function:

<body onload="console.log('Welcome to my home page!');">

As it is generally not recommended to mix the structure of the page (written in HTML) and manipulation of the DOM (written in JavaScript), the JavaScript parts will be grouped together here, and separated from the HTML.

For example, the following function creates a new <h1> element, adds text to that element, and then adds it to the tree for the document:

<html>
  <head>
    <script>
       // run this function when the document is loaded
       window.onload = function() {

         // create a couple of elements in an otherwise empty HTML page
         const heading = document.createElement("h1");
         const heading_text = document.createTextNode("Big Head!");
         heading.appendChild(heading_text);
         document.body.appendChild(heading);
      }
    </script>
  </head>
  <body>
  </body>
</html>