TOC PREV NEXT INDEX

domref


DOM Examples

This chapter provides some longer examples of web and XML development using the DOM. Wherever possible, the examples use common APIs, tricks, and patterns in JavaScript for manipulating the document object.

Example 1: height and width


The following example shows the use of the height and width properties alongside images of varying dimensions:

<html>
 
<head>
 
<title>image example</title>
 
<script language="javascript">
 
function init()
 
{
 
  var image = new Array();
 
  image[0] = document.getElementById('image1');
 
  image[1] = document.getElementById('image2');
 
  image[2] = document.getElementById('image3');
 
  var output = document.getElementById('output');
 
  var html   = '';
 
  var i;
 
  html = '<ul>';
 
  for (i = 0; i < image.length; i++)
 
      html += '<li>image' + (i+1) + ': height=' + image[i].height + ', width=' + image[i].width + ', style.height=' + image[i].style.height + ', style.width=' + image[i].style.width + '</li>';
 

 
  html += '</ul>';
 

 
  output.innerHTML = html;
 
}
 

 
</script>
 
</head>
 
<body onload="init()">
 

 
<p>Image 1: no height, width, or style <img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif"></p>
 
<p>Image 2: height=50, width=500, but no style <img id="image2" src="http://www.mozilla.org/images/mozilla-banner.gif" height="50" width="500"></p>
 
<p>Image 3: no height, width, but style="height: 50px; width: 500px;" <img id="image3" src="http://www.mozilla.org/images/mozilla-banner.gif" style="height: 50px; width:500px;"></p>
 

 
<div id="output">
 
</div>
 

height and width are also properties of the EMBED, OBJECT, and APPLET objects.

Example 2: Image Attributes


<html>
 
<head>
 
<title>border</title>
 
<script TYPE="text/javascript">
 
<!--
 
function border1(){document.IMG.setAttribute('border',20)}
 
function border2(){document.IMG.setAttribute('border',5)}
 
//-->
 
</script>
 
<style TYPE="text/css">
 
<!--
 
BODY { background-color: #ffffff }
 
//-->
 
</style>
 
</head>
 
<body>
 
*border
 
<hr>
 
<p>
 
<img SRC="image1.gif" ID="IMG" border="5" WIDTH="100" HEIGHT="100" ALT="border">
 
</p>
 
<form NAME="FORM">
 
<input TYPE="button" VALUE="Change" onClick="border1()">
 
<input TYPE="button" VALUE="Return" onClick="border2()">
 
</form>
 
<hr>
 
<p>
 
<font SIZE=-1>
 
Made by <a HREF="http://www.bekkoame.ne.jp/~hamba/webimage/java/java.html">MasahitoHamba</a>(<a HREF="mailto:hamba@bekkoame.ne.jp">hamba@bekkoame.ne.jp</a>).<br>
 
It's free to copy and arrange this sample.But please keep to regulation of <a HREF="http://cgi.din.or.jp/~hagi3/JavaScript/JSTips/Mozilla/MDSProject.htm" TARGET=msg>MDSProject</a>. <br>Last update 2001.01.14</font>
 
</body>
 
</html>
 

Example 3: Manipulating Styles


In this simple example, some basic style properties of an HTML paragraph element are accessed using the style object on the element and that object's CSS style properties, which can be retrieved and set from the DOM. In this case, you are manipulating the individual styles directly. In the next example (see Example 4), you can use stylesheets and their rules to change styles for whole documents.

<html>
 
<head>
 
<script>
 
function changeText() {
 
	p = document.getElementById("pid");
 
	p.style.color = "blue"
 
	p.style.fontSize = "18pt"
 
}
 

 
</script>
 
</head>
 
<body>
 
<p id="pid" 
onclick="window.location='http://www.cnn.com';" >linker</p>
 
<form>
 
<input value="rec" type="button" onclick="changeText();" />
 
</form>
 
</body>
 
</html>
 

Example 4: Using Stylesheets


The styleSheets property on the document object returns a list of the stylesheets that have been loaded on that document. You can access these stylesheets and their rules individually using the stylesheet, style, and CSSRule objects, as demonstrated in this example, which prints out all of the style rule selectors to the console.

ss = document.styleSheets;
 
for(ii=0;ii<ss.length;ii++) {
 
for(i=0;i<ss[0].cssRules.length;i++) {
 
   dump( ss[ii].cssRules[i].style.selectorText + "\n" );
 
}
 

For a document with a single stylesheet in which the following three rules are defined:

BODY { background-color: darkblue; }
 
P { font-face: Arial; font-size: 10pt; margin-left: .125in; }
 
#lumpy { display: none; }
 
This script outputs the following:
BODY
 
P
 
#LUMPY
 

Example 5: Event Propagation


This example demonstrates how events fire and are handled in the DOM in a very simple way. When the BODY of this HTML document loads, an event listener is registered with the top row of the TABLE. The event listener handles the event by executing the function l_func, which changes the value in the bottom cell of the table.

However, l_func also calls an event object method, stopPropagation, which keeps the event from bubbling any further up into the DOM. Note that the table itself has an onclick event handler that ought to display a message when the table is clicked. But the l_func method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended.

<html>
 
<head>
 
  <style>
 
    #t-daddy { border: 1px solid red }
 
    #t1 { background-color: pink; }
 
  </style>
 
  <script>
 
  function l_func(e) {
 
    t2 = document.getElementById("t2");
 
    t2.innerHTML = "three";
 
    e.stopPropagation(); 
 
    // this ought to keep t-daddy from getting the click. 
 
  }
 

 
  function load() {
 
    el = document.getElementById("t");
 
    el.addEventListener("click", l_func, false);
 
  }
 
  </script>
 
</head>
 
<body onload="load();">
 
<table id="t-daddy" onclick="alert('hi');">
 
  <tr id="t">
 
     <td id="t1">one</td>
 
  </tr>
 
  <tr><td id="t2">two</td></tr>
 
</table>
 
</body>
 
</html>
 

Example 6: getComputedStyle


This example demonstrates how the DOM document.defaultView.getComputedStyle() method can be used to get the styles on an element that aren't set in-line or with JavaScript (e.g., element.style.backgroundColor="lightblue"). These latter types of styles can be retrieved with the more direct style = element.style property, a list of which properties is listed in the DOM Style Reference of this book (see DOM CSS Properties List). See also the style property in the DOM Elements Reference.

getComputedStyle() returns a ComputedCSSStyleDeclaration object, whose individual style properties can be referenced with this object's getPropertyValue() method, as the following example document shows.

<html>
 
<head>
 
  <title>getComputedStyle</title>
 
  <script>
 
   function cStyles() {
 
     div = document.getElementById("d1");
 

 
     t1 = document.getElementById("t1");
 
     h_style = document.defaultView.getComputedStyle(div, '').getPropertyValue("height");
 
     t1.setAttribute("value", h_style);
 

 
     t2 = document.getElementById("t2");
 
     w_style = document.defaultView.getComputedStyle(div, '').getPropertyValue("width");
 
     t2.setAttribute("value", w_style);
 

 
     t3 = document.getElementById("t3");
 
     b_style = document.defaultView.getComputedStyle(div, '').getPropertyValue("background-color");
 
     t3.setAttribute("value", b_style);
 
  }
 
  </script>
 
  <style>
 
    .d { margin-left: 10px; background-color: lightblue; height: 20px; max-width: 20px; }
 
  </style>
 
</head>
 

 
<body>
 
<div id="d1" class="d">&nbsp;</div>
 
<p>&nbsp;
 

 
<blockquote>
 
  <button onclick="cStyles();">getComputedStyle</button>
 
  height<input id="t1" type="text" value="1"  />
 
  max-width<input id="t2" type="text" value="2"  />
  bg-color<input id="t3" type="text" value="3"  /></pre>
 
</blockquote>
 

 
</body>
 
</html>
 

Example 7: Displaying Event Object Constants


This example shows how to use the DOM to create a table in which all of the constants in the event object and their values are displayed. It shows off several useful aspects of the DOM, including the Event.prototype property, which allows you to get to the properties of a particular object, a good pattern for iterating over the properties in that prototype, and the values of the constants themselves displayed in the table. Note that the middle range of these constants are the character codes that represent the actual keys pressed during the event (and fetchable with the charCode property).

Load the following code as a web page to see the event object constants.

<?xml version="1.0" ?>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
 
<!--
 
 * ***** BEGIN LICENSE BLOCK *****
 
 * Version: NPL 1.1/GPL 2.0/LGPL 2.1
 
 *
 
 * The contents of this file are subject to the Netscape Public License
 
 * Version 1.1 (the "License"); you may not use this file except in
 
 * compliance with the License. You may obtain a copy of the License at
 
 * http://www.mozilla.org/NPL/
 
 *
 
 * Software distributed under the License is distributed on an "AS IS" basis,
 
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 
 * for the specific language governing rights and limitations under the
 
 * License.
 
 *
 
 * Contributor(s):
 
 *   Alexander J. Vincent <jscript@pacbell.net>
 
 *
 
 * Alternatively, the contents of this file may be used under the terms of
 
 * either the GNU General Public License Version 2 or later (the "GPL"), or 
 
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 
 * in which case the provisions of the GPL or the LGPL are applicable instead
 
 * of those above. If you wish to allow use of your version of this file only
 
 * under the terms of either the GPL or the LGPL, and not to allow others to
 
 * use your version of this file under the terms of the NPL, indicate your
 
 * decision by deleting the provisions above and replace them with the notice
 
 * and other provisions required by the GPL or the LGPL. If you do not delete
 
 * the provisions above, a recipient may use your version of this file under
 
 * the terms of any one of the NPL, the GPL or the LGPL.
 
 *
 
 * ***** END LICENSE BLOCK ***** * -->
 

 
<html xmlns="http://www.w3.org/1999/xhtml" >
 
<head><title></title>
 
<script language="JavaScript" type="text/javascript">
 
<!--
 
function respond() {
 
// creating a table 
 
    var table = document.createElement("table")
 
    table.setAttribute("border", "1")
 
    var tbody = document.createElement("tbody")
 

 
    var y = 0
 
    var tr = document.createElement("tr")
 
    var td = document.createElement("th")
 
// reusing the same variable name in the loop
 

 
// begin table heading information
 
    td.appendChild(document.createTextNode("Index"))
 
    tr.appendChild(td)
 

 
    td = document.createElement("th")
 
    td.appendChild(document.createTextNode("Property Name"))
 
    tr.appendChild(td)
 

 
    td = document.createElement("th")
 
    td.appendChild(document.createTextNode("Property Value"))
 
    tr.appendChild(td)
 

 
    tbody.appendChild(tr)
 
// end table heading information
 

 
    for (property in Event.prototype) {
 
        if (property == property.toUpperCase()) {
 
// adding a new row for each property of the event object
 
            tr = document.createElement("tr")
 
            td = document.createElement("td")
 
            td.appendChild(document.createTextNode(y))
 
// which property number it happens to be
 
            tr.appendChild(td)
 
            y++
 

 
            td = document.createElement("td")
 
            var td_text = document.createTextNode(property)
 
// the property name
 
            td.appendChild(td_text)
 
            tr.appendChild(td)
 

 
            td = document.createElement("td")
 
            var td_text = document.createTextNode(Event.prototype[property])
 
// the property value
 
            td.appendChild(td_text)
 
            tr.appendChild(td)
 

 
            tbody.appendChild(tr)
 
            }
 
        }
 
    table.appendChild(tbody)
 
    document.body.appendChild(table)
 
    }
 
//-->
 
</script>
 
</head>
 

 
<body onload="respond()">
 
<!-Results after clicking on the button:
 
The this object is myInput.
 
Index    Property Name Property Value
 
0        type          click
 
1        target        [object HTMLInputElement]
 
...
 
-->
 
</body>
 
</html>
 

Netscape Communications
http://developer.netscape.com
TOC PREV NEXT INDEX