Aims:
window
object represents the browser window
document
object represents the document
being displayed
location
object represents the URL of the
document being displayed
history
object represents the window's
recently visited URLs
links[]
- all hyperlinks in the document
images[]
- all img
elements
anchors[]
- all a
elements
with a name
or id
attribute
forms[]
- all form
elements
elements[]
- controls on a form, i.e.
input
, textarea
,
select
or button
elements
document.forms[0].elements[0]
document.forms[0].elements[1]
firstChild
lastChild
childNodes
(returns an array)previousSibling
nextSibling
parentNode
getElementById(…)
document.forms[0].childNodes[1].childNodes[1]
document.getElementById("btns").childNodes[3].childNodes[1]
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'; }
Snippets from animal.html
Note it references a file of JavaScript
<html> <head> <meta charset="utf-8" /> <title>Which animal are you?</title> <script type="text/javascript" src="year_validate.js"> </script> </head> <body> <form action="animal.php" method="get"> <input type="text" name="year" id="year" /> <input type="submit" /> </form> <div id="errors"> </div> </body> </html>
animal.php
, the PHP scriptNote 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.' );
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; } }