HTML and CSS Reference
In-Depth Information
Writing HTML Content
The content within an HTML element is also part of the object tree. One way of access-
ing and changing this content is by using the
innerHTML
property. For example, if the
first
h1
heading in a document is written using the HTML code
<h1>The <em>Japanese</em> Puzzle Factory</h1>
then the expression
document.getElementsByTagName(“h1”)[0].innerHTML
returns the text string
The <em>Japanese</em> Puzzle Factory
. Notice that both text and
HTML tags are part of the
innerHTML
property. To change the content of that heading,
you'd change the value of the
innerHTML
property, as in the following code:
var heading1 = document.getElementsByTagName(“h1”)[0];
heading1.innerHTML = “<i>Hanjie Puzzle</i>”;
After running this code, the first
h1
heading in the document would contain the text
Hanjie Puzzle
nested within an
i
element. Changing the value of the
innerHTML
prop-
erty also overwrites whatever content is currently contained within the selected object,
so you should be careful when using it to rewrite the content of elements that already
exist in a Web document. In the next tutorial, you'll learn ways to modify the structure
and content of elements within a Web document without overwriting the content that
already exists.
Using the
innerHTML
Property
Now that you've learned how to reference elements within a Web document and how
to change their content, you'll use that knowledge to display the hanjie puzzles that
Rebecca has designed for her Web site. To do this, you'll run a function named init()
when the page is initially loaded by a browser. You'll add the event handler attribute for
this function to the opening
<body>
tag in the HTML file now.
To insert the event handler:
◗
1.
Within the opening
<body>
tag in the
hanjie.htm
file, insert the following
attribute:
onload=”init()”
◗
2.
Save your changes to the file.
Next, you'll create the init() function. The function will display the title, hint, difficulty
level, and Web table for the first of the three puzzles. Rebecca already has placed the
following elements in her Web page to contain this information:
<h1>Hanjie</h1>
<div id=”hint”></div>
<div id=”rating”></div>
<figure id=”puzzle”></figure>
The puzzle title will be placed within the first
h1
element on the page. The hint and
rating values will be displayed within
div
elements with
id
attribute values of
hint
and