DOM Scripting
The Document Object Model
Contents
UserAgents reads a document as a set of nodes and attributes, which constitute the Document Object Model. The Document Object Model supported by a browser should be tested to see if it supports the particular functionality we want to run from our scripts. To test for browser support of the W3C DOM use the following:
if (!document.getElementById || !document.createTextNode) {return;}
To keep your scripts separate from your html, store your script in an exteranl '.js' file and link to the script in the header of your html documents:
<script type="text/javascript" src="script.js"><script>
To avoid functions clashing, write your functions as methods of objects:
myScript = new Object();
myScript.init=function() {
some code
}
myScript.validate=function() {
some code
}
//call init function
myScript.init();
//call validate function
myScript.validate();
Or using the object literal
var myScript={
variable:'value',
variable2:'another value',
anArray:['one', 'two', 'three'],
init:function(){some code},
validate:function(){some code},
}
Using DOM
Top BottomDOM provides methods to read and change attributes:
- getAttribute('attributeName')
- setAttribute('attributeName')
DOM also provides methods to change elements:
- document.createElement('element')
- Creates a new element node
- document.createTextNode('string')
- Creates a new text node
- node.appendChild(newNode)
- Adds newNode as a new child node to node
- newNode = node.cloneNode(bool)
- Creates newNode as a copy of node. If 'bool' is set to true, the clone includes copies of all the child nodes and attributes of the original
- node.insertBefore(newNode,oldNode)
- inserts newNode as a child of node before oldNode
- node.removeChild(oldNode)
- removes child node 'oldNode' from node
- node.replaceChild(newNode,oldNode)
- replaces oldNode child of node with newNode
Get Elements
Top BottomUsing getElementsByTagName and getElementsById you can reach any element in a document. getElementsByTagName is a method of any element and getElementsById is a method of document.
Elements and nodes occur in parent, child and sibling relationships. Two important properties of nodes are NodeName and NodeType. NodeType 1 is an element and NodeType 3 is a text node. For elements the NodeName is the name of the element, and for text nodes the NodeName is '#text'. NodeValue is the value of the node: null if it is an element and the text content if it is a text node. For instance the text content of the third list Item can be read with 'document.getElementsByTagName('li')[2].firstChild.nodeValue'
You can also set the attribute value: linkItem.firstChild.nodeValue='Whatever'. Or you can use the preferred method syntax: linkItem.firstChild.setAttribute('href') = 'Whatever'
nextSibling property of a list item in an unordered list shows the next list item in Internet Explorer, but in Firefox the nextSibling is a text node with a new line as the content. To get to the next list item in a modern browser use nextSibling.nextSibling
Examples:
function findElements() {
var listElements=document.getElementsByTagName('li');
var paragraphs=document.getElementsByTagName('p');
var msg='This document contains ' + listElements.length + ' list items\n';
msg+='and ' + paragraphs.length + ' paragraphs.';
alert(msg);
var thirdListItem = listElements[2];
alert('Third List Item is ' + thirdListItem.firstChild.nodeValue);
alert('Changing Third list item text!');
document.getElementsByTagName('li')[2].firstChild.nodeValue = 'Hello World';
var myLinkedItem = document.getElementById('linkedItem');
alert('Parent of Parent of linked item: ' +
myLinkedItem.parentNode.parentNode.nodeName);
alert('Content of next sibling of linked item: ' +
myLinkedItem.parentNode.nextSibling.nextSibling.firstChild.nodeValue);
alert('Link address of linked item: ' + myLinkedItem.href);
}
window.onload = findElements;Writing Text
Top BottomAvoid annoying alert popups and using document.write
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" http://www.w3.org/TR/html4/strict.dtd"> <html dir="ltr" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>DOM Example</title> <script type="text/javascript" src="checkdate.js"></script> </head> <div id="content"> <h1>Events Search</h1> <form action="eventssearch.php" method="post" onsubmit="return checkDate();"> <p> <label for="date">Date in the format DD/MM/YYYY:</label><br /> <input type="text" id="date" name="date" /> <input type="submit" value="Check " /> <br />(example 26/04/1965) <span class="error"> </span> </p> </form> </div>
And the source script:
function checkDate() {
if (!document.getElementById || !document.createTextNode) {
return;
}
var dateField=document.getElementById('date');
if (!dateField) {
return;
}
var errorContainer=dateField.parentNode.getElementsByTagName('span')[0];
if (!errorContainer) {
return;
}
var checkPattern = new RegExp("\\d{2}/\\d{2}/\\d{4}");
var errorMessage='';
errorContainer.firstChild.nodeValue='';
var dateValue=dateField.value;
if (dateValue == '') {
errorMessage='Please provide a date.';
}
else if(!checkPattern.test(dateValue)) {
errorMessage='Please provide the date in the defined format.';
}
if (errorMessage!='') {
errorContainer.firstChild.nodeValue=errorMessage;
dateField.focus();
return false;
}
else {
return true;
}
}
//window.onload = checkDate();
