Adding a new note
The actual note itself is just a small box with standard text and a link that enables the user to edit the text later, as seen in Figure 2.
This is the equivalent of the following HTML:Listing 3. The target HTML
Adding the actual element uses standard DOM techniques, as seen in Listing 4:Listing 4. Adding the new note element
In this case, you've changed the button so that it causes the execution of
makeNewNote() rather than
incrementCurrent(), though that function is still in use within
makeNewNote(). First, you use
getElementById() to get a reference to the main
div element that ultimately will contain the note. You then use the
document object to create a new element, just as you would do in any other language, with the name of
div. To set the
id attribute, you simply use the
setAttribute() method on the new element.
Each note will have a unique
id attribute, so you need to know what the current total is. To get this
information, you start at the level of the form element itself. From
there, you retrieve the list of children. The first (with an index of
0) is the text, and the second (with an index of
1) is the actual
But what about
.value? Isn't that a typo? Shouldn't it be
Actually, no. Remember, elements don't have values. At first glance, it might
look as though I'm mixing DOM and DHTML properties, but in actuality,
the element retrieved here is not just an implementation of
org.w3c.dom.Element, it's an implementation of
which also includes a value property that represents the value of the
form field. In this way, DOM mimics some (though not all) of the
properties that were available through DHTML.
Once the attribute is set, you simply append the new
div element to the
mainDiv element, where it will appear. Or at least, it would if it had any presentation properties or text.
To add the style information, you will actually use the DHTML style object:Listing 5. Adding style information
The result is a small yellow box with a blue border, as shown in Figure 3.
Notice that the
property of the note depends on the current number of notes, which
increments after each note is added. This way, you can add a series of
boxes, as shown in Figure 3.