Dot Syntax Alternatives
Besides the
dot syntax, there are 2 other ways to refer to HTML elements with JavaScript.
The getElementById() Reference
The first uses the standards compliant method, "getElementById()", where the value of the HTML id attribute is placed within the parenthesis to identify which element is being referred to.
<form id="blueForm">
<input type="text" name="myText" id="blueElm">
The JavaScript reference for the text field in the above form would be:
document.getElementById("blueElm")
As you can see, it is a much shorter reference than the dot path with its listing of every containing object. Most of these lessons don't use the getElementById() method. This is because there still exists all over the web, scripts which use the dot path (I'm a believer in learning by example), and you must use the dot path when working with custom made objects. However, many CSS identifiers are applied to HTML elements which do not fit into any object containment hierarchy (other than the document). In these cases, it is nesscessary - as you'll see when you reach the dynamic html section of this site. You will not be hurt or have to unlearn anything by using both techniques.
The Array Notation Reference
The 2nd way to refer to HTML elements is by using array notation. We'll study arrays in depth in a later
tutorial, so for now I'll just show you the syntax.
There are several DOM objects that are assumed in any given HTML document whether they exist or not. A numeric index (look up label) is assigned to each existing object of the same type, along with a generic reference to it. For instance, lets assume a page contains 3 images. Below is the array notaion reference for each:
document.images[0]
document.images[1]
document.images[2]
The numeric index is assigned according to an element's position in the flow of the document, starting with 0. In other words, the first image on the page will have the "0" index assigned to it, the second image "1", and so on.
Array notation when referring to forms is a little more hairy. This is because both forms and form elements are categorized into their own arrays. If I have 2 forms on a page, and I want access to the 1st element in the 2nd form, my reference looks like this:
document.forms[1].elements[0]
As you'll see later on, there are times when array notation is more convenient, and sometimes even neccessary.
>>
Objects, Properties and Methods
>>
The Dot Syntax
>>Dot Syntax Alternatives
>>
JavaScript Statements
>>
JavaScript Placement: Script Tags and Source Files
>>
JavaScript Placement: Event Handlers