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.

The following simple example illustrates using the DOM Document API – specifically, it illustrates using the body property of the Document API to change:

  • the document's text color
  • the document's background color
  • the documents's link color (that is, the color of any hypertext links anywhere in the document)
<html>
<head>
  <title>Simple Document API example</title>
  <script>
    function setBodyAttr(attr, value) {
      if (document.body) document.body[attr] = value;
      else throw new Error("no support");
    }
  </script>
</head>
<body>
  <div>
    <form>
      <p><b><code>text</code></b></p>
      <select onChange="setBodyAttr('text',
        this.options[this.selectedIndex].value);">
        <option value="black">black</option>
        <option value="red">red</option>
      </select>
      <p><b><code>bgColor</code></b></p>
      <select onChange="setBodyAttr('bgColor',
        this.options[this.selectedIndex].value);">
        <option value="white">white</option>
        <option value="lightgrey">gray</option>
      </select>
      <p><b><code>link</code></b></p>
      <select onChange="setBodyAttr('link',
        this.options[this.selectedIndex].value);">
        <option value="blue">blue</option>
        <option value="green">green</option>
      </select>
      <small>
        <a href="http://some.website.tld/page.html" id="sample">
          (sample link)
        </a>
      </small>
    </form>
  </div>
</body>
</html>

Result