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 ...

Get JavaScript: The Definitive Guide, 6th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.