The Document Object Model

Lecture Notes for CS 142
Winter 2014
John Ousterhout

  • Additional reading 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.
    • Simple example: <p>Sample <b>text</b> display</p>
    • Key links: parentNode, nextSibling, prevSibling, firstChild, lastChild.
    • nodeName property is element type (uppercase: P, DIV, etc.) or #text.
    • getAttribute, setAttribute methods, etc.
  • How to find HTML elements to manipulate?
    • Approach #1: work down through the DOM hierarchy starting at the top:
      element = document.body.firstChild.nextSibling.firstChild;
      element.setAttribute...
      
    • Better solution: ids
      • Include an id attribute in HTML elements that will be referenced dynamically:
        <div id="div42">...</div>
        
      • Then, in Javascript code:
        element = document.getElementById("div42");
        element.setAttribute...
        
      • 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 attributes of element); 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);
    
    But, setting innerHTML is usually simpler and more efficient.
  • Logging to console (for debugging):
    console.log("Reached point A");
    

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
    • The position of an element is determined by the upper-left outside corner of its margin.
    • Coordinates are relative to element.offsetParent, which is not necessarily the same as element.parentNode (see below).
  • 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.
    • The origin inside an offsetParent (for positioning descendants) is just inside the upper-left corner of its border.
  • Positioning context: coordinate system for specifying element locations
    • Each element has an offsetParent (some ancestor element).
    • When an element is positioned, coordinates such as element.style.left are relative to its offsetParent.
    • Default offsetParent is the <body> element.
    • Some elements define a new positioning context:
      • position CSS attribute is absolute (element is explicitly positioned)
      • position CSS attribute is relative (element is positioned automatically by the browser in the usual way)
      • This element will become the offsetParent for all its descendents (unless overridden by another positioning context)
      • See positionExamples.html for examples
  • Dimensions:
    • Read element.offsetWidth and element.offsetHeight; these include contents, padding, border, but not margin.
    • Write element.style.width and element.style.height
  • 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.