JavaScript tutorial - Browser inspecific referencing

Navigation

Skip navigation.

Site search

Site navigation

JavaScript tutorial

Printing

Other tutorials

Browser inspecific referencing

Note that to avoid referencing problems, no two elements should ever be given the same name or id. The only exception is form inputs which can share names.

Global references

Variables are referenced simply by typing their name, or by using window.variableName for global variables.

Functions are referenced simply by typing their name, or by using window.functionName for global functions.

'window' (or 'self') may be used to reference the global object for the current document, regardless of what scope your script is running in. If your script is running in another script and you are having trouble referencing global variables because a local variable uses the same name, this problem can be quickly solved by adding 'window.' to the start of the variable name. For example window.myvariable

By a similar nature, you can use 'this' to represent the current object. By default, 'this' will be the window object. If you are writing the script as part of a HTML event handler, 'this' will be the element that detected the event. For example, this can be used to alert the value of the text input:

function myFunction(x) { window.alert(x.value); }
...
<input type="text" onkeypress="myFunction(this)">

Using this same function from a script running in the global scope, the word 'this' refers to the window object. The window object does not have a value property, so the function would alert 'undefined'.

However, if the onkeypress method is activated manually, the word 'this' once again refers to the input, so the function will alert the value of the input:

document.forms[0].elements[0].onkeypress();

Frameset references

There are four very useful references that refer to parts of a frameset. These are 'window' or 'self', 'window.parent', 'window.top' (window is usually omitted) and the window.frames collection.

self and window
These refer to the global object of current web page.
parent
Refers to the window object of the page that is holding the current page in a frameset.
top
Refers to the window object of the page at the top of the frames hierarchy.
window.frames[nameOrNumberOfFrame]
Refers to a frame or iframe held by the current page.

With iframes (if the browser supports them) you have to use the extra word 'window' on the end to reference the window object of the document contained by the iframe (there are alternatives, but this one works in all browsers that support iframes, making it superior to all other techniques, since they only work in a selection of browsers):

window.frames[nameOrNumberOfFrame].window

If the page is the only page being displayed, top, parent, self and window will be equal. If the page is being held within a frameset, self and top will not be equal. If the page is the page containing the frameset, and it itself is not being held within a frameset, self and top will be equal. If someone is loading your page into their frameset and you don't want them to, you can use the self-top relationship to remove your page from their frameset and replace their frameset page with your page using:

if( self != top ) { top.location.replace(self.location.href); }

Note, I could have used this:

if( self != top ) { top.location.href = self.location.href; }

However, that makes the browser add the new entry into its history, so if they clicked their back button, they would be forwarded back to your page again. Unfortunately, Gecko browsers (Mozilla/Firefox/Netscape 6+) will only allow the second option as they have very high security levels relating to cross-site scripts.

Note that using scripts to force pages in and out of framesets is a very bad idea. It causes usability problems for many users, breaks search engines, and annoys your visitors. I know you know how to do it, but that does not mean that you should.

With all frames, the name is set using the name="nameOfFrame" attribute in the <frame ...> tag. The number is automatically generated by the browser in the order that the frames are defined in the HTML, beginning at 0.

To fully reference the window object of another frame when inside a frameset, use one of these:

From there, you can reference items inside that document using document.whatever

parent.frames['otherframename'].document.images['imagename'].src = "sample.gif";

Take, for example, the following frame page structure. The main page - main.html - (which by default has no name, although it can be set with JavaScript, or by opening the page with target="newName") contains two frames; 'left' and 'right'. 'left' contains the page 'links.html'. 'right' contains a page - inner.html - containing a further two frames; 'banner' and 'mainpart'. The locations of 'banner' and 'mainpart' are upper.html and lower.html respectively. The names of the files are irrelevant, but it helps me to explain the structure to you. This produces the following frame tree structure:

       unnamed frame (main.html)
   ____________|____________
  |                         |
left (links.html)         right (inner.html)
                  __________|______________
                 |                         |
              banner (upper.html)      mainpart (lower.html)

The following examples use the frames collection, although any of the above syntaxes would be fine.

If a script were running in main.html, it would be able to reference the window and document objects of lower.html using this:

window.frames['right'].frames['mainpart']
window.frames['right'].frames['mainpart'].document

If a script were running in lower.html, it would be able to reference the window object of links.html using either of these:

window.parent.parent.frames['left']
window.top.frames['left']

Attempting to access the contents of a frame before they have loaded will cause an error. In all browsers, the window object will not exist for that frame unless the page has loaded.

if( !window.frames['nameOfFrame'] ) { window.alert( 'Frame has not loaded' ); }

This algorithm also works with iframes, without requiring any changes.

Forms

Note that this changes in Netscape 4 and other layers browsers if the form is put inside a positioned element. See the section on Element contents for more details. Since these browsers are no longer in use, this behaviour can be safely ignored.

To fully reference a form, use document.formname for a form that was defined with the name="nameOfForm" attribute in the <form ...> tag, or document.forms[number_of_form] either should work. The number is generated automatically by the browser in the order that the forms are defined in the HTML, beginning at 0.

To fully reference an input, use any of these:

reference_to_form.inputname
reference_to_form.elements['inputname']
reference_to_form.elements[number_of_input_(not_image_input)]

Name is defined using the name="nameOfInput" attribute in the <input ...>, <textarea ...>, <button ...> or <select ...> tags. Number is generated automatically by the browser in the order that the inputs are defined in the HTML, beginning at 0.

You can read or write the value of text inputs and textareas with their 'value' property. See the section on The JavaScript object for a full list of what parts of a form can be read or changed.

If more than one input of any kind in the same form share the same name (as is common with radio button inputs), they must be referenced using the numerical array associated with that name. The array will contain an entry for each input with that name, in ascending order of how they appear in the source of the document, beginning at 0. For example, if a radio button has the name 'mybutton', it can be referenced using this:

document.nameOfForm.mybutton

But if two radio buttons share the name 'mybutton', the second button (for example) can be referenced using this:

document.nameOfForm.mybutton[1]

This will be the case for any input type, even if inputs of different types share the same name. In practice, radio buttons will almost always share a name, and checkboxes may occasionally share a name. Even if inputs share a name, they will still have individual entries in the elements collection.

For select boxes, each individual option can be referenced using input_name.options[number_of_option]. For example:

if( document.myForm.mySelect.selectedIndex == 1 ) {
  document.myForm.mySelect.options[3].selected = true;
  if( !document.myForm.myRadio[1].checked ) {
      document.myForm.myRadio[2].checked = false;
    document.myForm.myRadio[1].checked = true;
    document.myForm.myRadio[0].checked = false;
  }
}

You can reference the value of an option tag with '.value' and the text it displays with '.text'. You can also find out how many options there are by using the '.length' property of the options collection.

Note, setting a select option to null will remove it from the select box:

document.forms[number_of_form].mySelect.options[0] = null;

All other options will have their index numbers adjusted to reflect this change. To add or replace one, use this:

document.forms[number_of_form].mySelect.options[number] = new Option('text','value');

Most commonly, number used is the length of the collection, as that will add the new option onto the end:

document.forms[number_of_form].mySelect.options.length

Warning: although the selectInputObject.selectedIndex property should be read-write, it is read-only in Internet Explorer 4. If this causes problems, you car use this:

selectInputObject.options[index].selected = true;

Images

Note that this changes in Netscape 4 and other layers browsers if the image is put inside a positioned element. See the section on Element contents for more details. Since these browsers are no longer in use, this behaviour can be safely ignored.

To reference an image, use any of these:

Name is defined using the name="nameOfImage" attribute in the <image ...> tag. Number is generated automatically by the browser in the order that the images are defined in the HTML, beginning at 0.

Note, if you compare document['imagename'].src to a string constant, you will find that in some browsers it may be the same whereas in others it is not. This is because some browsers will give the image src in the format 'myimage.gif' whereas others may give it in the format 'http://mydomain.co.uk/myimage.gif':

if( document['imagename'].src == "pig.gif" ) {
...
if( document['imagename'].src == myImage.src ) {

A solution to this is to use the string method 'indexOf()'. If the parameter is not contained within the string, the method returns -1, else it returns the position of the first occurrence of the parameter within the string. For example:

if( 'http://mydomain.co.uk/myimage.gif'.indexOf('myimage.gif') +  1 ) {
  //This will be executed
}
if( 'http://mydomain.co.uk/myimage.gif'.indexOf('yourimage.gif') +  1 ) {
  //This will not be executed
}
if( 'http://mydomain.co.uk/myimage.gif'.indexOf('image.gif') +  1 ) {
  //This will be executed. BE WARNED, this may cause a problem
}

Links, anchors and areas

Note that this changes in Netscape 4 and other layers browsers if the link is put inside a positioned element. See the section on Element contents for more details. Since these browsers are no longer in use, this behaviour can be safely ignored.

To reference an <a ...> element, there are two ways (excluding those provided by the DOM). If the name attribute is set, so making the element an anchor (used in <a href="#nameOfLink">) you can refer to it using this:

document.anchors[number_of_<a>_element]

Alternatively, if the href attribute is set, you can refer to it using this:

document.links[number_of_<a>_element]

Number is generated automatically by the browser in the order that the links or anchors are defined in the HTML, beginning at 0.
As <area ...> tags also have the href attribute, they may also be accessed using the links collection, but not the anchors collection. If an <a ...> element has both the the href and name attributes set, it will appear in both collections, although its index may be may not be the same in each. In layers browsers, any links or anchors referred to using the anchors collection will have only the name property available. The collection provides access to the anchors purely for the purpose of changing the name, used when setting the location with location.hash.

Last modified: 19 March 2011

  1. Previous
  2. Next
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.