Using JavaScript to create dynamic HTML pages

The Document Object Model (DOM)

JavaScript is made up of numereous built in Objects which are used for a range of tasks. The Maths and Concatenation exercise made use of the Math object, for example.

Another of JavaScripts built in objects is called the document object. In order for JavaScript to be able to work with and to manipulate HTML it need to have some way of accessing and exploring the HTML page it is attached to. The document object model provides a framework under which JavaScript can navigate through, select, replace and add to existing areas of the HTML page.

Dot notation

Dot notation allows JavaScript objects to function. A dot in a JavaScript statement means that the element on the right of the dot is a property or a method of the object on the left of the dot.

//object.method
document.write("hello");

var myName = "Andrew";
//object.property
myName.length;

Dot notation is the primary method of navigating through and affecting the DOM (and so the HTML page). The document object is the reference JavaScript uses to refer to the HTML document it is attached to as a whole. Every JavaScript statement which references or alters part of a HTML document needs to begin with a reference to the document object.

Within the document object are a number of child object which refer to parts of the HTML document. For example, document.images holds a reference to all of the images contained in that specific HTML page. Also already covered is the method document.write() which can be used to insert text into a HTML page. Other areas of the document object which will be covered later on in this course.

<img src="images/happyface.png" alt="Happy face example" name="happyFace" />

<script type="text/javascript">
// find the URL image linked by the <img ... name="happyFace" />
// tag and load it into a variable 
    var imageURL = document.images["happyFace"].src;

// chop the URL down to a manageable size
// lastIndexOf("/") returns the last instance of a /
// in the URL, and substring is used to return a smaller 
// part of a string, in this case chop off all bar the 
// filename (the bit after the last /).
    imageURL = imageURL.substring(imageURL.lastIndexOf("/"));

// write the URL of the image into the HTML page
    document.write("<p>The URL is " + imageURL + "</p>");
</script>

Live example:

Happy face example

Using the document object model, JavaScript can write HTML to a web page allowing pages to be created with dynamic information such as the result of calculations, or a response to user input, which would be impossible using HTML alone.

The example below uses the JavaScript date object to update this page with the current date and time.

<script type="text/javascript">
	document.write("<p>The date is " + Date() + "</p>");
</script>

Live example:

The document.write(); method is used to add content into the HTML page. This method now works across all browser platforms (it didn't at one point) when compiled along with the page (as this example is).

If the page requires that a portion of it's content be updated in response to something the user does this technique will not suffice. Using document.write(); in this way will result in a new page being created and the text added, as in this example.

There are a few methods for changing the content of a page after the page has loaded and been presented to the user, the simplest and most flexible of which innerHTML.

innerHTML

This is a very flexible way for a programmer to access and change parts of a HTML page using JavaScript. innerHTML was pioneered by Microsoft in the late 1990s and despite never being officially included in the JavaScript specification it has won acceptance and inclusion in ALL major browser platforms (certainly all the ones you need to worry about).

When innerHTML is used on the left of an assignment (remember the assignment operator is = ) the right of the assignment operator is used to replace the specified area of the HTML page. For example:

pageElement.innerHTML = "<p>Hello World</p>"

... would result in the contents of pageElement being replaced with a paragraph containing the phrase "Hello World".

When used on the right of an assignment, innerHTML returns the content of the specific area of the HTML page so that JavaScript may examine or change it. For example:

// document.firstChild = the DTD (which has no content of it's own)
// nextSibling of the DTD = <html> (which contains the HTML page) 
var wholeHTMLPage = document.firstChild.nextSibling.innerHTML;

When innerHTML is used in conjunction with another global method, getElementById(), the result is complete ease of access to more or less the entire HTML page.

Before we see innerHTML in action let's have a quick look at getElementById().

getElementById()

This method allows JavaScript easy access to any portion of a HTML page in which a specific ID has been used. For example:

document.getElementById("header");

Once the tag with the specific ID requested has been returned it can be assigned to a variable, like this:

var headerBlock = document.getElementById("header");

... or manipulated directly, like this:

document.getElementById("header").innerHTML = "<p>Hello World</p>";

Putting it all together

In the following example the page loads and waits for the user to click the button labled "Enter your name". When they do a JavaScript function called amendExample is run by the onClick() event handler attached to the button. The amendExample function lanuches a prompt box to collect the user's name. The function then uses getElementById() to reference the part of the HTML page it will amend. Finally the function changes the content of the specified HTML block to reflect whatever the user had typed into the prompt box.

<div id="innerHTMLexample" type="text/javascript">
    Your name will appear here
</div>

<input type="button" onclick="amendExample()" value="Enter your name" />

<script type="text/javascript">
function amendExample() {
    
// run a prompt box to collect the user's name
    var userName = prompt("Enter your name");
    
// create a variable called htmlChunk and assign it the HTML 
// page element specified by the ID "innerHTMLexample"
    var htmlChunk = document.getElementById('innerHTMLexample');
        
// change the HTML inside htmlChunk (and so "innerHTMLexample") 
// to whatever is returned from a prompt box asing for the user's name.
    htmlChunk.innerHTML = 'Hello ' + userName;				
}
</script>

Live example:

Your name will appear here

Of course, when you get a bit more practice with JavaScript it is possible to write all of the above as one single line directly into the event handler in the <input> tag. In doing this the script no longer needs to be wrapped in a function. ;)

<div id="innerHTMLexample" type="text/javascript">
    Your name will appear here
</div>

<input type="button" onclick="document.getElementById('innerHTMLexample')
.innerHTML = 'Hello ' + prompt('Enter your name');" 
value="Enter your name" />

Try it if you don't believe me!

Exercise!

Now open the dynamic page exercise and work through it.

You may also use the JavaScript scratch pad to try out code quickly.