Netscape 6, Part II: Animation: Setting innerHTML - Doc JavaScript | WebReference

Netscape 6, Part II: Animation: Setting innerHTML - Doc JavaScript

Netscape 6, Part II: Animation

Setting innerHTML

The innerHTML property of elements in IE is not part of the W3C DOM. Nevertheless, in response to customers' requests, Mozilla- and Gecko-based browsers (such as Netscape 6) decided to support it in builds dated May 19, 2000 or later (Mozilla M16 and later, Netscape 6 PR2 and later). Let's look at an example. We want to update a counter by clicking a button. Let's look at the following code sample:

<DIV ID="counter">Number of clicks = 0</DIV>
<INPUT TYPE="button" VALUE="Increment Counter"
var hits = 0;
function updateMessage() {
  hits += 1;
  document.getElementById("counter").innerHTML =
    "Number of clicks = " + hits;
// -->

which renders like this:

Number of clicks = 0

The function updateMessage() is called every time the user clicks the button. The number of hits is incremented by one, and the content of the DIV counter is updated by the innerHTML property, via a simple assignment. Notice the usage of getElementById() which is common to both Netscape 6 and Internet Explorer.

The innerHTML property is called so because it holds the content of an HTML tag, from the end of the opening tag, to the beginning of the closing tag. Here is the tag above:

<DIV ID="counter">Number of clicks = 0</DIV>

The content of the tag between the end of the opening DIV to the beginning of the closing DIV is:

Number of clicks = 0

This is the content of innerHTML in the tag above. The innerHTML property may include HTML tags. Let's look at the following tag:

<DIV ID="counter2"><FONT COLOR="red">Number of clicks = 0</FONT></DIV>

The content of innerHTML here is:

<FONT COLOR="red">Number of clicks = 0</FONT>

We can change the color of the counter, for example, by setting the innerHTML as follows:

document.getElementById("counter2").innerHTML = "<FONT COLOR='purple'>
Number of clicks = " + hits2 + "</FONT>";

Try it now:

Number of clicks = 0

Next: How to move objects horizontally

Produced by Yehuda Shiran and Tomer Shiran
All Rights Reserved. Legal Notices.
Created: December 18, 2000
Revised: December 18, 2000