<!-- JavaScript:DOM code snippet 2. -->
<!-- Navigating the document tree structure. -->
<!-- Gain access to the html root element with 'document.documentElement' and
use of the lastChild, firstChild, nextSibling and nodeValue properties to then
navigate down and traverse across the tree structure. -->
<!-- Gain access to the text content of a header and paragraph text values. -->
<!-- Problems with browsers interpreting white space differently:
hence all white space has been removed between the elements in the
body section of this document. -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<!-- Code source: http://www.justfigures.co.uk/ -->
<!-- A resource for web developers using XHTML, CSS, JavaScript, PHP -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>View code snippet page</title>
<script language="JavaScript" type="text/javascript">
/* navigating the document tree structure */
function retrieveValues()
{
/* gain access to the html root element */
var htmlNode = document.documentElement;
/* navigate down and traverse across the tree structure */
var bodyNode = htmlNode.lastChild;
var h1Node = bodyNode.firstChild;
var h1TextValue = h1Node.firstChild.nodeValue;
var pNode = h1Node.nextSibling;
var pTextValue = pNode.firstChild.nodeValue;
/* write the text values to alert windows */
window.alert(h1TextValue);
window.alert(pTextValue);
}
</script>
</head><body><h1>Level 1 Heading text: last child of html node, first child of body node, first child of h1 node.</h1><p>Paragraph text: next sibling of h1 node, first child of p node.</p>
<form name="getTextValues" id="getTextValues">
<input type="button" value="Click me to access the h1 and p node text values" onclick="retrieveValues()" /></form>
</body>
</html>