1. Home
  2. Computing & Technology
  3. JavaScript

The Javascript DOM

3. getElementById

clr gif
Join the Discussion

Questions? Comments?

More of this Feature

Introduction Collections

The main way of accessing specific parts of an already existing web page is by using the getElementById method attached to the document. This particular method provides us with a way to access a particular container within the document. That container must already exist at the time that we try to access it. (We will look at adding to the page in later tutorials).

The first thing that we need to do in order to be able to access a specific container using this method is to mark the container so that we can uniquely identify which container it is that we want to refer to. We do this by adding an extra attribute to the HTML tag that we want to identify. his extra attribute is id (hence the name getElementById).

<div id="content">

Each container that we want to be able to access from Javascript needs to have an id attribute added to it if we are to use this method to access it. An id can contain any combination of letters and numbers as long as it starts with a letter and as long as no two containers on the page have the exact same id. Each id on the page must be unique.

Once we have marked all of the containers within the page that we want to be able to access from Javascript we can then access them from Javascript quite easily. The following example shows how we can access the div in our above HTML example.

var content = document.getElementById('content');

The variable content is now a Javascript object that refers to the HTML container object on the web page. This object now has access to all of the properties of the HTML container and we can retrieve those properties for use in our Javascript as well as change the values of those properties in order to affect how the container is displayed on the web page.

We'll look more at how to access the properties of a container object in the next tutorial.

Explore JavaScript
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. JavaScript

©2009 About.com, a part of The New York Times Company.

All rights reserved.