The Document Object Model

Lecture Notes for CS 142
Fall 2010
John Ousterhout

  • Readings for this topic:
    • None.
    • However, www.w3schools.com is a good source of reference material.
    • The most authoritative overall reference on the DOM, with good coverage of browser differences, is Dynamic HTML: The Definitive Reference by Danny Goodman (Third Edition).
  • The Document Object Model (DOM)
    • Representation of an HTML document at run time as a collection of Javascript objects and methods
    • Allows a Web page to be queried and modified dynamically under the control of Javascript
  • Overall document structure:
    • window (global)
    • window.document
    • window.document.body
  • All of the major components of HTML (elements, raw text, etc.) have a common set of properties and methods ("Node" is the term used for these things):
    • Many properties and methods are common to all nodes.
    • Key links: parentNode, nextSibling, prevSibling, firstChild, lastChild.
    • nodeName property is element type (uppercase: P, DIV, etc.) or #text.
    • Simple example: <p>Sample <b>text</b> display</p>
    • getAttribute, setAttribute methods, etc.
  • How does Javascript relate to an HTML document?
    • Approach #1: work down through the DOM hierarchy starting at the top:
      node = document.body.firstChild.nextSibling.firstChild;
      node.setAttribute....
      
    • Better solution: ids
      • Include an id attribute in elements that will be referenced dynamically:
        <div id="div42">...</div>
        
      • Call document.getElementById("div42") in the Javascript code.
      • Need to ensure that each id is really unique within a page.

Basic DOM Operations

  • Change the content of an element:
    element.innerHTML = "This text is <i>important</i>";
    
    Replaces any existing content (but retains existing element attributes); causes node structure of DOM to change.
  • Change an image (e.g., toggle appearance on clicks):
    img.src="newImage.jpg";
    
  • Make element visible or invisible (e.g., for expandable sections):
    • Invisible:
      element.style.display = "none";
      
    • Visible:
      element.style.display = "";
      
      Or, to be safe, save the original style.
  • Change the appearance of an element (e.g., highlight when mouse passes over):
    • Change its class:
      element.className = "active";
      
    • Use separate CSS styles for each appearance.
    • Generally a bad idea to modify style directly in the element, such as
      element.style.color = "#ff0000";
      
  • Redirect to a new page:
    window.location.href = "newPage.html";
    
  • Create a new element and add it to an existing one:
    element = document.createElement("P");
    parent.insertBefore(element, sibling);
    
    or,
    parent.appendChild(element);
    
  • Simple dialog boxes:
    alert("Please click to continue");
    if (confirm("Are you sure you want to ...?")) {
        ...
    }
    
    name = prompt("Enter user name here:");
    

Coordinates and Positioning

  • Coordinates (needed, for example, to position a pop-up menu next to an existing element, or for drag-and-drop):
    • The origin is at the upper left; y increases as you go down.
    • Read location with element.offsetLeft, element.offsetTop These are relative to element.offsetParent, which is not necessarily the same as element.parentNode (only divs, tables and a few other elements act as offset parents)
    • Dimensions: offsetWidth and offsetHeight include contents, padding, border, but not margin.
  • Positioning elements:
    • Normally elements are positioned automatically by the browser as part of the document.
    • To pull an element out of the document flow and position it explicitly:
      element.style.position = "absolute";
      element.style.left = "40px";
      element.style.top = "10px";
      
      In this case, the element no longer occupies space in the document flow.
  • How to learn what DOM facilities are available?
    • Browse the DOM section at www.w3schools.com, look through the properties and methods for various elements, such as window and document.
    • Warning: w3schools doesn't seem to be absolutely complete (some features not in Internet Explorer are omitted). The book Dynamic HTML: The Definitive Reference, by Danny Goodman is more complete.