1. Technology

What is the ID Attribute?

Unique Identifiers within Web Pages


According to the W3C, the ID attribute in XHTML:

assigns a name to an element. This name must be unique in a document.

This is a very simple description of a very powerful attribute. The ID attribute performs several actions for Web pages:

  • A style sheet selector
    This is the function most people use the id attribute for. Because they are unique, you can be sure you'll be styling just the one item on your Web page when you style using an id property.
  • Named anchors for linking to
    Now, most modern Web browsers allow you to target precise locations in your Web documents by pointing to the id at the end of the URL. You simply add the id to the end of the page URL, preceded by a pound-sign (#).
  • A reference for scripts
    If you write any Ajax or DHTML, you will want to use the id attribute so that you can make changes to the precise element on the page with your scripts.
  • A name for object elements
    This acts the same way as for scripts, only you identify objects like Flash or Java.
  • Other processing
    The id allows you to process your Web documents in whatever way you need to. For example, you might extract the HTML into a database, and the id attribute identifies fields.

Rules for Using the ID Attribute

There are a few rules you must follow to have a valid document that uses the id attribute anywhere in the document:

  • The id must start with a letter (a-z or A-Z)
  • All subsequent characters can be letters, numbers (0-9), hyphens (-), underscores (_), colons (:), and periods (.).
  • Each id must be unique within the document. Why?

Using the ID Attribute

Once you have identified a unique element of your Web site, you can use style sheets to style just that one element:

<p id="paragraph1">This is my first paragraph.</p>
p#paragraph1 { background: #0cf; }

You can also link to that specific element without adding any <a> tags:

<a href="#paragraph1">link to the first paragraph</a>

Reference that paragraph in your scripts with the "getElementById" JavaScript method:


If you have been avoiding the id attribute, you are missing out on a powerful tool for styling, linking, and scripting your Web pages.

©2014 About.com. All rights reserved.