1. Technology

Why must the ID attribute be unique on each page?


Question Mark Key

Question Mark Key

Image courtesy hdoddema from StockXchng #619007.
Question: Why must the ID attribute be unique on each page?
Charlie asks:
Standards specify that any given id name can be referenced only once within a page or document.... It seems to me that there is really no functional difference between class and id selectors, and that one may as well use id all the time simply because it's easier to type. Is there a subtle reason for not doing so?

You can use the ID selector as an anchor reference in your Web pages, but only if you only have it once on the page. In other words, if you have a div with an ID "number1" you can then point to that section of your page with an anchor URL of <a href="#number1">number 1</a> Granted, you can still do that if you have the ID listed multiple times, but only the first instance will be linked to.

A less pragmatic reason to use an ID once in every page is so that you as the Web designer know which section is which. Every page has a unique identifier (the URL/filename) - and this gives you a little more granularity in finding sections of your Web site. That means that if you want to style only one part of one Web page in a specific way, you know you can if you use the IDs correctly - because the ID attributes will be unique on every page.

A forward thinking reason is that in the future, browsers might not display duplicated ID elements as they do now, or as you expect them to.

Finally there is the "because I said so" reason. :) If you want your Web pages to validate as XHTML or HTML, then you should have unique IDs on your pages.

©2014 About.com. All rights reserved.