The Sysadmin Notebook  

Sitemap

DOM Example

Example Use of DOM to Analyse Document

<!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="exampleFindElements.js"></script>
</head>
<div id="content">
	<h1>Heading</h1>
	<p>Using 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 elemtnt, 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'</p>
	<p>You can also set the attribute value, eg linkItem.firstChild.nodeValue='Whatever'. Or you can use the preferred
	method syntax: linkItem.firstChild.setAttribute('href') = 'Whatever'</p>
	<h2>Subheading</h2>
	<ul id="eventsList">
		<li>List 1</li>
		<li><a href="http://www.cpan.org" id="linkedItem">Linked List Item</a></li>
		<li>List 3</li>
		<li>List 4</li>	
	</ul>
	<p>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</p>
	<p>Paragraph</p>
</div>

and the script source file:


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;