//object.method document.write("hello"); var myName = "Andrew"; //object.property myName.length;
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.
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.
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".
// 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().
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>";
Try it if you don't believe me!
Now open the dynamic page exercise and work through it.