1. Technology
Send to a Friend via Email

The Javascript DOM

4. Accessing Properties

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Introduction Collections getElementById

Exactly which properties are available when you access an HTML container from a web page via the getElementById method depends on the type of element that theid is attached to. Most commonly an id will be attached to a div tag but sometimes you will find it more convenient to attach it to a different tag.

The following code illustrates some of the basic properties are available for all objects. (The properties are shown coded in alert statements simply because it produces a short piece of code that you can run to illustrate the effect, they can be coded in whatever way that you need to to achieve your desired result).

var x = document.getElementById('myfield');
alert(x.nodeName);
alert(x.nodeType);
alert(x.tagName);

In some instances these refer to an object contained within our currently referenced container or an object in which our current container can be found. In those instances we can then reference the properties of that object.

alert(x.firstChild.tagName);
alert(x.lastChild.tagName);
alert(x.nextSibling.tagName);
alert(x.parentNode.tagName);
alert(x.previousSibling.tagName);

In addition to the above properties, any of the attributes attached to the tag can also be accessed by referencing that attribute name. There are a couple of things to keep in mind when trying to reference attributes like this. Any attributes that contain hyphens in their name will have the hyphen removed and the following letter converted to uppercase when referenced from Javascript and the class attribute is referenced using the className property as class is a reserved word in Javascript.

All of the attributes and all of the child nodes of our object can also be accessed if required from the attributes and childNodes arrays that are also available.

alert(x.attributes[0]);
alert(x.childNodes[0].id);

As well as being able to retrieve the current values of the attributes on the tag, we can also assign a new value to the attribute from within our Javascript by referencing the appropriate property on the left of an assignment statement.

document.getElementById('myfield').title = 'New tooltip text';

We will look at a couple of particularly useful properties in more detail in the next couple of tutorials.

©2014 About.com. All rights reserved.