The DOM

Today's agenda:

The DOM

tree shaped structure built out of all of the HTML elements in a page, accessible via JavaScript

Visualizing the tree


    <html>
      <head>
        <title> ... </title>
      </head>
      <body>
        <h1> ... </h1>
        <div>
          <p> ... </p>
        </div>
      </body>
    </html>
    

HTML

DOM

Document Object Model (DOM)

a set of JavaScript objects that represent each element on the page

How to get DOM elements in JS:

Getting a DOM element in JS:


HTML


var pTag = document.getElementById("october");

JavaScript

What's inside a DOM object?

For starters, the HTML attributes. This HTML:


<img src="images/puppy.png" alt="A fantastic puppy photo"/>

HTML

Has a DOM object (let's call it puppyImg) with these two properties:


<p>See our <a href="sale.html" id="saleslink">Sales</a> today!</p>
<img id="icon" src="images/borat.jpg" alt="Borat" />
<caption class="photo user-upload">Beauty.</caption>

HTML


var icon    = document.getElementById("icon");
var theLink = document.getElementById("saleslink");
var caption = document.querySelector("caption");

JavaScript

Property Description Example
tagName element's HTML tag icon.tagName is "IMG"
className CSS classes of element caption.className is "photo user-upload"
src URL target of an image icon.src is "images/borat.jpg"
href URL target of a link theLink.href is "sale.html"

innerHTML property

All DOM elements have a property called innerHTML that has the contents of the HTML tag as a string:


<ul id="dr-seuss">
    <li>Thing 1</li>
    <li>Thing 2</li>
</ul>

HTML


var elm = document.getElementById("dr-seuss");
// elm.innerHTML : "\n    
  • Thing 1
  • \n
  • Thing 2
  • \n"

    JavaScript

    Ok, what do we do with DOM objects?

    Set their properties, and the page changes in response

    This is how give behavior to web pages: use JavaScript to manipulate the DOM by changing the properties of DOM elements

    
    <a id="fb-link" href="http://www.facebook.com">Facebook</a>
    

    HTML

    Before the JavaScript runs, we'd see:

    Facebook

    And after we run this Javascript:

    
    var link = document.getElementById("fb-link");
    link.innerHTML = "MySpace is back in a really big way."
    

    JavaScript

    We'd see:

    MySpace is back in a really big way.

    Unobtrusive JavaScript

    Unobtrusive JavaScript

    Obtrusive event handlers (bad)

    <button onclick="okayClick();">OK</button>
    

    HTML

    // called when OK button is clicked
    function okayClick() {
        alert("booyah");
    }
    

    JavaScript

    Attaching an event handler in JavaScript code

    objectName.onevent = function;
    
    <button id="ok">OK</button>
    

    HTML

    var okButton = document.getElementById("ok");
    okButton.onclick = okayClick;
    

    JavaScript

    When does my code run?

    <html>
    <head>
        <script src="myfile.js" type="text/javascript"></script>
    </head>
    <body> ... </body>
    </html>
    

    HTML

    var x = 3;
    function f(n) { return n + 1; }
    function g(n) { return n - 1; }
    x = f(x);
    

    myfile.js -- JavaScript

    A failed attempt at being unobtrusive

    <html>
    <head>
        <script src="myfile.js" type="text/javascript"></script>
    </head>
    <body>
    <div><button id="ok">OK</button></div> 
    (... more html ...)
    

    HTML

    var btn = document.getElementById("ok");
    btn.onclick = okayClick;  // this is bad: btn is null at this point
    

    myfile.js -- JavaScript

    The window.onload event

    function functionName() {
        // put code to initialize the page here
    }
    
    // instruct window to run the function when the page has loaded:
    window.onload = functionName;
    

    JavaScript

    An unobtrusive event handler

    <button id="ok">OK</button>   <!-- (1) -->
    

    HTML

    // called when page loads; sets up event handlers
    function pageLoad() {
        var ok = document.getElementById("ok"); // (3)   
        ok.onclick = okayClick;
    }
    
    function okayClick() {
        alert("booyah");                        // (4)
    }
    
    window.onload = pageLoad;                   // (2)
    

    JavaScript

    Common unobtrusive JS errors

    Anonymous functions

    function(parameters) {
        ... statements ...;
    }
    

    Anonymous function example

    window.onload = function() {
        var ok = document.getElementById("ok");
        ok.onclick = okayClick;
    };
    
    function okayClick() {
        alert("booyah");
    }
    

    JavaScript

    window.onload = function() {
        document.getElementById("ok").onclick = function() {
            alert("booyah");
        };
    };
    

    Unobtrusive styling

    function okayClick() {
        this.style.color = "red";       // <-- bad style
        this.className = "highlighted"; // <-- better style
    }
    

    HTML

    .highlighted { color: red; }
    

    CSS

    The danger of global variables

    var count = 0;
    function incr(n) {
        count += n;
    }
    function reset() {
        count = 0;
    }
    
    incr(4);
    incr(2);
    console.log(count);
    

    Enclosing code in a function

    function everything() {
        var count = 0;
        function incr(n) {
            count += n;
        }
        function reset() {
            count = 0;
        }
    
        incr(4);
        incr(2);
        console.log(count);
    }
    
    everything(); // call the function to run the code
    

    JavaScript

    The "module pattern"

    (function() {
        statements;
    })();
    

    Module pattern example

    (function() {
        var count = 0;
        function incr(n) {
            count += n;
        }
        function reset() {
            count = 0;
        }
    
        incr(4);
        incr(2);
        console.log(count);
    })();
    

    JavaScript "strict" mode

    "use strict";
    
    ...your code...
    

    JavaScript

    JS Skeleton

     
    
    

    HTML

    (function() {
        window.onload = function() {
           // phew! your code goes here
        };
    })();
    

    JavaScript