HTML and CSS Reference
In-Depth Information
specifically, when the JavaScript in the
script
element is being executed (called
execution time
or
runtime)
. This is what I mean by creating HTML dynamically. For the quiz application, I created two types
of elements that well add, with the names “country” and “cap”. For each of these, we insert an element of
type
div
, a general element type that suits our purposes here. (Be aware that HTML5 has added several
other types—for example,
header
,
footer
,
article
, and
section
—that convey more specific meaning
and should be considered for your applications. Chapter 1 shows one use of
section
, and in Chapter 10,
Ill show
footer
.)
The div is a block type, meaning it can contain other elements as well as text, and it is displayed with line
breaks before and after. Table 6-2 shows methods well use.
Table 6-2.
Methods for Creating HTML
Code
Explanation
createElement
Creates the HTML element
appendChild
Adds the element to the document by appending it to something in the
document
getElementbyID
Gets a reference to the element
One trick needed for applications such as this is to come up with unique
id
values for the elements that
are created. Well do this using a variable thats incremented for each set of country and capital. The id
value consists of that number, converted to a string and then preceded by a "c" or a "p". Why a "p"?
Because I'm using "c" for country and "p" came to mind when thinking of capital. By the way, the id values
dont have to be numbers or take any particular form. As you see, in our application, they are single letters
followed by numbers.
The matching country and capital city will have the same number so we can use the
id
values to check for
a match. We use a
String
method,
substring
, that extracts a portion of any string of characters. Lets
look at a couple of examples. To use
substring
, you specify the starting position and, optionally, one
more than the ending position. That is, the extracted string starts at the first parameter and goes up until
the second. If our code doesnt include the second parameter, the extract goes to the end of the string.
Suppose you had a variable
var class ;
for course or class names. Most colleges use specific patterns for such names, such as three letters for
department and then perhaps four numbers to indicate the specific course. Now lets suppose the variable
class
has been assigned the value "MAT1420". In that case,
class.substring(0,3)
would produce "MAT"
class.substring(3)
would produce "1420"
class.substring(3,7)
would produce "1420"
class.substring(3,6)
would produce "142"
class.substring(3,4)
would produce "1"