Cover by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

O'Reilly logo

Selecting Document Elements

Most client-side JavaScript programs work by somehow manipulating one or more document elements. When these programs start, they can use the global variable document to refer to the Document object. In order to manipulate elements of the document, however, they must somehow obtain or select the Element objects that refer to those document elements. The DOM defines a number of ways to select elements; you can query a document for an element or elements:

  • with a specified id attribute;

  • with a specified name attribute;

  • with the specified tag name;

  • with the specified CSS class or classes; or

  • matching the specified CSS selector

The subsections that follow explain each of these element selection techniques.

Selecting Elements By ID

Any HTML element can have an id attribute. The value of this attribute must be unique within the document—no two elements in the same document can have the same ID. You can select an element based on this unique ID with the getElementById() method of the Document object. We’ve already used this method in both Chapter 13 and Chapter 14:

var section1 = document.getElementById("section1");

This is the simplest and most commonly used way to select elements. If your script is going to manipulate a certain specific set of document elements, give those elements id attributes, and look up the Element objects using that ID. If you need to look up more than one element by ID, you might find the getElements() function of Example 15-1 useful.

Example 15-1. Looking ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required