CIT041J Index > Lecture Notes - Part 4

CIT041J Lecture Notes - Part 4

Accessing HTML from JavaScript

The easiest way to access an HTML element from JavaScript is to give the element an id attribute. The value of this attribute must begin with a letter, and must contain only digits, letters, and underscores. So, for example, if you wanted to give JavaScript access to the following paragraph in your document:

Here it is!

You would write this markup:

<p id="para1">Here it is!</p>

Once you have done this, your JavaScript functions can call the document.getElementById() function and pass the id as a parameter. JavaScript then returns an object that represents the paragraph.

For example, here is code that will display the HTML that is inside paragraph id="para1":

function showPara() {
  var obj = document.getElementById('para1');
  var content = obj.innerHTML; // get the HTML inside this object
  alert(content);
}
Try it.

You can also change the contents of a paragraph by setting the innerHTML:

function changePara() {
  var obj = document.getElementById('para1');
  obj.innerHTML = "Now it's different."; // set the HTML inside this object
}
Try it.

You use the innerHTML to access or modify the content of any element that can contain HTML or text (such as <p>, <li>, <span>, etc.).

Forms are done in a slightly different manner; you will read more about that later.

The document.getElementById function is part of the document object model (DOM). Go to this tutorial for an in-depth view of the DOM. If you want to see all the properties a document has and all the built-in functions (methods) for a document, see this reference.

The onload attribute

On this page, the innerHTML was accessed and changed only when you clicked a link. Sometimes, you will want to set content dynamically as soon as a page is loaded, without user action required. In that case, you add the onload attribute to the <body> tag. See an example of such a page, which shows you the date and time every time you load or reload the page.

This page requires JavaScript.