Java Reference
In-Depth Information
var messages = xmlDoc.getElementsByTagName(“daily”);
var dateobj = new Date();
var today = dateobj.getDay();
return messages[today].firstChild.nodeValue;
}
First, use the
getElementsByTagName()
method to retrieve the
<daily/>
elements. As you already
know, this will return a node list of all the
<daily/>
elements. The next task is to fi nd a numerical
representation of the day of the week. Do this by fi rst creating a
Date
object and using its
getDay()
method. This gives you a digit between
0
and
6
, with
0
being Sunday,
1
being Monday, and so on; the
digit is assigned to the
today
variable. Finally, use that variable as an index of the
messages
node list
to select the correct
<daily/>
element and retrieve its text.
You may have noticed that
xmlDoc
in
getDailyMessage()
isn't declared anywhere in the head of the
HTML document. It is used in
createDocument()
, but that variable is declared within the context of
the function. You actually declare the global
xmlDoc
in the body of the HTML page.
<body>
<div id=”messageContainer”></div>
<script type=”text/javascript”>
var xmlDoc = createDocument();
xmlDoc.async = false;
xmlDoc.load(“motd.xml”);
document.getElementById(“messageContainer”).innerHTML = getDailyMessage();
</script>
</body>
</html>
The fi rst HTML element found in the body is a
<div/>
element with an
id
of
messageContainer
. Use
this
<div/>
to display the message of the day.
Following the
<div/>
is the last
<script/>
element in the page. In this code block, you create a DOM
document and assign it to the global
xmlDoc
variable. Then load the
motd.xml
fi le synchronously and
set the message container's
innerHTML
to the message of the day by calling
getDailyMessage()
.
Try It Out Tabulating Doggie Data
In this example, you will write an application that uses an XML document containing data about one of
your author's dogs. Open your text editor and type the following:
<html>
<head>
<title>Chapter 12: Example 11</title>
<script type=”text/javascript”>
function createDocument()
{
var xmlDoc;
if (window.ActiveXObject)
{
var versions =