The Document Object Model

Derek Bridge

Department of Computer Science,
University College Cork

The Document Object Model


The Document Object Model (DOM)

The Legacy DOM (simplified)

[A diagram showing a simplified version of the Document Object Model]

Legacy DOM objects

Legacy DOM collections

Legacy DOM example

The W3C DOM (simplified)

W3C DOM example

W3C DOM example: changing the document

Examples from the previous lecture of using the W3C DOM

function make_it_smile()
	document.getElementById("face").src = 'smile.jpg';

function make_it_frown()
	document.getElementById("face").src = 'frown.jpg';

Example: the HTML form

Snippets from animal.html
Note it references a file of JavaScript

        <meta charset="utf-8" />
	    <title>Which animal are you?</title>
        <script type="text/javascript" src="year_validate.js">

        <form action="animal.php" method="get">   
            <input type="text" name="year" id="year" />  
            <input type="submit" />
        <div id="errors">


Example: animal.php, the PHP script

Note that this PHP script does no validation of user data

require_once( 'output_functions.php' );
$animals = array
    ('Monkey', 'Rooster', 'Dog', 'Pig', 'Rat', 'Ox', 'Tiger', 
     'Rabbit', 'Dragon', 'Snake', 'Horse', 'Goat');
$year = (int) $_GET['year'];
output_header( 'Your Chinese animal (roughly)', 'stylesheet.css' );
$index = $year % 12;
output_paragraph( "You are a {$animals[$index]} (roughly speaking)" );
output_footer( 'Chinese Animals Ltd.' );

Example: year_validate.js, the client-side JavaScript

This JavaScript validates the user's data before submitting it to animal.php
Note the use of the W3C DOM

if ( window.addEventListener )
    window.addEventListener("load", init, false);
else if ( window.attachEvent )
    window.attachEvent("onload", init);

function init()
    document.forms[0].onsubmit = validate;

function validate()
    var year;
    year = document.getElementById("year").value;
    if ( ! /^\d{4}/.test(year) ||  year > (new Date()).getFullYear() )
        document.getElementById("errors").firstChild.nodeValue = 
            'ERROR: You must enter a valid year';
        return false;

Alternative versions