Spring Semester 2003


Lecture Notes Extra: Javascript and The Document Object Model

Here's (first) a summary of these notes:

And now the actual notes.

A. What are Nodes?

When a web browser renders a document, it creates objects in memory to represent the many parts of the document. DOM1 provides a model for how the objects of a web page relate to one another. The term for an object in DOM1 is node. Consider the simple statement below:

<p>My name is Larry Bjord.</p>
The <p> tag is an element node. The text contained by the <p> tag pair is a text node. The two nodes exist in a parent-child relationship. The element node is a parent, the text node is a child. Now consider a more complex example.
<p>I am a child node of p.</p><b>I am a child node of b.</b>
As an exercise draw a picture for this example.

<p>No, McGee - Swedish. Olsen is a <em>Swedish</em> name.</p>
The first two examples included element nodes and text nodes.

A third type of node is the attribute node. Consider this example:

<div align="left">
  <p> I am a child of p, which is a child of div. 
      <b> I am a child of b, which is a child of p. </b> 
  </p> 
</div>
Each node has properties that represent its place in the hierarchy. The parentNode property of a child node creates a reference to the node that contains the child node. The firstChild property of a parent node creates a reference to the first child node. The lastChild property creates a reference to the last child node. The childNodes array contains one element for each child node. For example, say we create a variable p to represent the first <p> element (the one with id="p1" in the document represented below:
<html>
  <head>
    <title>DOM Nodes</title>
  </head>
  <body>
    <p id="p1">
      Hi, my name is Bjorn Borg -  Bork, Bork! .
    </p> 
    <p align="center" id="p2">
      <b> Aligned Bold </b> 
    </p> 
  </body>
</html>
The table that follows shows the relationships that can be represented using the various node properties and the childNodes array.

Code Description
var theNode = document.
                firstChild.
                  childNodes[1].
                    firstChild
The first <p> element in the <body> tag is the first child of the second child (childNodes[1]) of the first child of the document. This type of reference is awkward. The next row shows a much more elegant approach.
var theNode = document.
                getElementById("p1")
If an element has an ID attribute, it is much easier to create a reference to it. This code uses the getElementById() method of the document object to place the <p> element with id="p1" into the variable theNode.
theNode.parentNode
<body> is the parent node of theNode
theNode.parentNode.parentNode
<html> is the parent node of the parent node of theNode
theNode.parentNode.parentNode.firstChild
<head> is the first child node of the parent node of the parent node of theNode
theNode.firstChild.theNode.childNodes[0]
This refers to the text node "Hi, my name is Bjorn Borg - " - which is what very few of us can say (in good faith).
theNode.childNodes[1].firstChild
This refers to the text node "Bork, Bork!", which is a typical Swedish (Chef) greeting.
theNode.parentNode.childNodes[1].firstChild
This refers to the attribute node align, which is the first child of the second child of the parent node of theNode.

The most practical thing you can gain from the table above is an understanding of how much easier your life will be if you simply add the ID attribute to your elements and create references using the document.getElementByID() method. Just be sure to make each ID attribute unique in your document. B. Dynamically Changing Node Content.

There are six parts to this section:

  1. Changing the text in the text nodes
  2. Removing and adding text nodes
  3. Creating element nodes
  4. Changing attribute nodes
  5. Using loops to change text nodes
  6. Examining node methods and properties
We're going to cover some of them, the ones most relevant to us.

B.1 Changing the text in the text nodes

We start with an example:

<html>
  <head>
    <title>
      DOM Nodes (Part I) 
    </title>

    <script type="text/javascript" language="JavaScript">
      function changeGreeting() {
        var theNode = getObject("greeting"); 
        var newGreeting = window.prompt("Type a greeting.", "Yo, baby!"); 
        theNode.firstChild.nodeValue = newGreeting; 
      }
      function getObject(elementID) {
        return document.getElementById(elementID); 
      }
    </script>

  </head>
  <body bgcolor="white">
    <p>
      <span id="greeting">Hi!</span> My name is Larry Bjord. 
    </p> 

    <p> 
      <a href="javascript:changeGreeting();">Change Greeting</a> 
    </p> 
  </body> 
</html>
(Try it here).

This simple example would be enough for you to finish Homework Four.

But let's keep going.

B.2 Removing and adding text nodes

<html>
  <head>
    <title>
      DOM Nodes (Part II) 
    </title>

    <script type="text/javascript" language="JavaScript">
      function changeName() { 

        var newName = window.prompt("Type a name:", "The Swedish Chef"); 

        emptyNode("name"); 
        var theNode = getObject("name"); 

        var newText = document.createTextNode(newName); 
        theNode.appendChild(newText); 
      }

      function emptyNode(elementID) {
        var theNode = getObject(elementID); 
        for (i = 0; i < theNode.childNodes.length; i++) {
          theNode.removeChild(theNode.childNodes[i]); 
        }
      }

      function getObject(elementID) {
        return document.getElementById(elementID); 
      }


    </script>

  </head>
  <body bgcolor="white">

    <p> 
      <span id="greeting">Hi, there!</span> 

      My name is

      <span id="name">Larry Borg Bjork</span>. 

    </p> 

    <p> 
      <a href="javascript:changeName();">Change Name</a> 
    </p> 
         
  </body> 
</html>
Try this here.

B.3 Creating element nodes

<html>
  <head>
    <title>
      DOM Nodes (Part III) 
    </title>

    <script type="text/javascript" language="JavaScript">
      function changeNameBold() { 

        var newName = window.prompt("Type a name:", "Mr. Grimbold"); 

        emptyNode("name"); 
        var theNode = getObject("name"); 

        var newText = document.createTextNode(newName); 

        var newElem = document.createElement("b"); 

        newElem.appendChild(newText); 
        theNode.appendChild(newElem); 

      }

      function emptyNode(elementID) {
        var theNode = getObject(elementID); 
        for (i = 0; i < theNode.childNodes.length; i++) {
          theNode.removeChild(theNode.childNodes[i]); 
        }
      }

      function getObject(elementID) {
        return document.getElementById(elementID); 
      }


    </script>

  </head>
  <body bgcolor="white">

    <p> 
      <span id="greeting">Hi, there!</span> 

      My name is

      <span id="name">Larry Borg Bjork</span>. 

    </p> 

    <p> 
      <a href="javascript:changeNameBold();">Change Name and Bold It</a> 
    </p> 
         
  </body> 
</html>
Try this here.

B.4 Changing attribute nodes

<html>
  <head>
    <title>
      DOM Nodes (Part IV) 
    </title>

    <script type="text/javascript" language="JavaScript">
      function changeAlignment(val) { 
        var theNode = getObject("greeting"); 
        theNode.setAttribute('align', val); 
      }

      function getObject(elementID) {
        return document.getElementById(elementID); 
      }
    </script>

  </head>
  <body bgcolor="white">

    <p id="greeting"> 
      Hi, there! My name is Larry Boerd Foerd.
    </p> 

    <p> 
      <b> 
        Align the Paragraph
      </b>
    </p> 

    <table cellpadding=6>
      <tr>
        <td> <a href="javascript:changeAlignment('left');">Left</a> 
        <td> <a href="javascript:changeAlignment('center');">Center</a> 
        <td> <a href="javascript:changeAlignment('right');">Right</a> 
    </table>
         
  </body> 
</html>
Try this here.

B.5 Using loops to change text nodes

<html>
  <head>
    <title>
      DOM Nodes (Part V) 
    </title>

    <script type="text/javascript" language="JavaScript">
      var counter = 0; 

      function countUp() {
        var theNode = getObject("thecount"); 
        counter++; 
        if (counter <= 100) {
          theNode.firstChild.nodeValue = counter;           
          window.setTimeout("countUp()", 50); 
        } else {
          counter = 0; 
        }
      }

      function getObject(elementID) {
        return document.getElementById(elementID); 
      }
    </script>

  </head>
  <body bgcolor="white">
    <p> 
       Here is a number: 
       <span id="thecount">0</span> 
       <br /> 
       <a href="javascript:countUp();">Click here to count up to 100.</a> 
       
    </p> 
  </body> 
</html>
Try this here.

B.6 Examining node methods and properties

DOM1 offers a remarkable degree of control over dynamic content.

The table below shows some useful properties and methods of DOM1.

Method or Property Example, Description, and Comments
appendChild() theNode.appendChild(othernode) This statement makes otherNode the last child of theNode. You can also use this method to move otherNode from one location in a document to another.
appendData()
caption
cellIndex
cells
childNodes[]
className
cloneNode()
createCaption
createElement()
createTextNode()
data
deleteCaption()
deleteCell()
deleteData()
deleteRow()
deleteTFoot()
deleteTHead()
disabled
documentElement
firstChild
getAttribute
getElementById
getElementsByTagName()
hasChildNodes()
href
id
innerHTML
insertBefore()
insertCell()
insertData()
insertRow()
lastChild
name
nextSibling
nodeName
nodeType
nodeValue
ownerDocument
parentNode
previousSibling
remove()
removeChild()
replaceChild()
rowIndex
rows[]
setAttribute
specified
splitText()
tagName
tBodies[]
tFoot
tHead
title
value

These are methods and properties of DOM1 that work reliably in modern browsers.


Last updated: Mar 27, 2003 by Adrian German for A348/A548