Java Reference
In-Depth Information
Try it Out Displaying Results in a Web Page
In this fi nal example, you'll discover how to write information directly to a web page using JavaScript.
This proves more useful when you're writing the results of a calculation or text you've created using
JavaScript, as you'll see in the next chapter. For now, you'll just write “Hello World!” to a blank page
using JavaScript:
<!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”>
<body >
<p id=”ResultsP”></p>
<script type=”text/javascript”>
// Script block 1
document.getElementById('ResultsP').innerHTML = 'Hello World!';
</script>
</body>
</html>
Save the page as ch1_examp3.htm to a convenient place on your hard drive. Now load it into your web
browser and you'll see Hello World! in the page. Although it would be easier to use HTML to do the
same thing, this technique will prove useful in later chapters.
The fi rst part of the page is the same as in our earlier examples, except the following line has been
added:
<!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”>
This lets the web browser know that you're using XHTML, the standard used throughout this topic. It
doesn't actually make any difference to the code; it would work just fi ne without the extra lines.
Consider this line:
<p id=”ResultsP”></p>
You'll notice the <p> tag has been given an id using the id attribute. This id must be unique in the web
page, because it is used by the JavaScript to identify the specifi c HTML element in the following line:
document.getElementById('ResultsP').innerHTML = 'Hello World!';
Don't worry if this seems complex at the moment; you'll learn more about how this works in later chap-
ters, especially Chapters 6 and 12. Basically, the code is saying, “Get me the document element with id
ResultsP and set the HTML inside that element to Hello World!”
It's important in your example that the code accessing the paragraph is after the paragraph. Otherwise,
the code would be attempting to access a paragraph before it existed in the page and would throw an
error.
Search WWH ::




Custom Search