Dot Notation and Square Bracket Notation

Contact Us or call 1-877-932-8228
Dot Notation and Square Bracket Notation

Dot Notation and Square Bracket Notation

In the first lesson of this course we took a look at two ways in which we can access elements in JavaScript: dot notation and square bracket notation. Let's review these concepts again, since we will use both tactics repeatedly throughout this course.

Dot notation lets us refer to hierarchical DOM elements starting with the top-most element (window, say) then a set of dot-separated names, referencing elements by their name or id. For instance, to get an input element with id fname inside a form with id form1, we might use the following:

window.document.form1.fname

If the form were the first form on the page, we could also refer to it this way:

window.document.forms[0].fname

Since a document can have multiple form elements as children, we can reference the specific form by its order on the page, as an element in the collection of forms. Arrays and collections in JavaScript start with index 0, so the first form on the page would be forms[0].

Similarly, we can reference objects with square bracket notation, where the argument of the brackets is the id of the element or the number-index of the element in a collection:

window['document']['form1']['fname']

// or

window['document']['forms'][0]['fname']

Both of the references above are equivalent to the dot-notation references we showed earlier and can be used interchangeably. With either dot notation or square bracket notation, keep in mind that the reference moves from general on the left to specific on the right. In our example, the window contains the document, which contains a form with id form1, which in turn contains an input element with id fname.

Next