0

Possible Duplicate:
Why can't I have a numeric value as the ID of an element?

Element's ID must begin with a letter ([A-Za-z]). But if I do something like

<td id='9'></td>

javascript can find such elements. So I do not understand why can't I start it with a number

Community
  • 1
  • 1
Oleksandr IY
  • 2,783
  • 6
  • 32
  • 53
  • It's quite a common rule for identifiers that they can contain numbers but not begin with them (same in TSQL and C# AFAIK). Not sure if there is any good reason for that. – Martin Smith Sep 14 '12 at 12:00
  • Class identifiers are allowed to start with a number, but ID identifiers are not. That is all. [CSS-tricks](http://css-tricks.com/ids-cannot-start-with-a-number/). – sp00m Sep 14 '12 at 12:02
  • give it a prefix like id="item_1" and you are fine, you can split all the ids with javascript for example ... –  Sep 14 '12 at 12:04

3 Answers3

4

The standard specifies that IDs must start with a letter. If browsers (or rather JavaScript engines) choose to ignore that requirement, then that's just the way it is. Browsers are really forgiving that way ...

Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
  • I think it's also worth noting that C-style programming languages, javascript included, cannot use variable names that start with a number because it causes confusion for the parser/compiler/interpreter. – Steven Hunt Sep 14 '12 at 12:02
1

HTML 4 normalizes indeed that

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

There's a long time browsers apply the much more permissive HTML5 norm, even if it's still not the official one :

Any string, with the following restrictions:

  • must be at least one character long
  • must not contain any space characters

But be careful as you may have problems with older browsers if not respecting the HTML4 norm. Note also that programmers, in most languages, are used to "usual id", that is more like what you had in HTML4. By using "unusual" id, you run the (not so great) risk to encounter libraries not able to handle them.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

If you deviate from the spec, you're running the risk that your code won't work in a browser that decides to follow the spec more tightly that the one that you're working with.

That may be fine, but it seems like an unnecessary risk, since you could avoid any such problems by preceding the number with some fixed string and maintain the semantics of a 'numeric' id.

Dancrumb
  • 26,597
  • 10
  • 74
  • 130